take.js 1016 B

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