take.js 1001 B

12345678910111213141516171819202122232425262728293031323334353637
  1. const {Transform} = require('stream');
  2. class Take extends Transform {
  3. constructor(options) {
  4. super(Object.assign({}, options, {writableObjectMode: true, readableObjectMode: true}));
  5. this._n = this._skip = 0;
  6. if (options) {
  7. 'n' in options && (this._n = options.n);
  8. 'skip' in options && (this._skip = options.skip);
  9. }
  10. if (this._skip <= 0) {
  11. this._transform = this._n > 0 ? this._countValues : this._doNothing;
  12. }
  13. }
  14. _transform(chunk, encoding, callback) {
  15. if (--this._skip <= 0) {
  16. this._transform = this._n > 0 ? this._countValues : this._doNothing;
  17. }
  18. callback(null);
  19. }
  20. _countValues(chunk, encoding, callback) {
  21. if (--this._n <= 0) {
  22. this._transform = this._doNothing;
  23. }
  24. this.push(chunk);
  25. callback(null);
  26. }
  27. _doNothing(chunk, encoding, callback) {
  28. callback(null);
  29. }
  30. static make(n) {
  31. return new Take(typeof n == 'object' ? n : {n});
  32. }
  33. }
  34. Take.make.Constructor = Take;
  35. module.exports = Take.make;