takeWhile.js 826 B

123456789101112131415161718192021222324252627282930313233
  1. 'use strict';
  2. const {Transform} = require('stream');
  3. const alwaysTrue = () => true;
  4. class TakeWhile extends Transform {
  5. constructor(options) {
  6. super(Object.assign({}, options, {writableObjectMode: true, readableObjectMode: true}));
  7. this._condition = alwaysTrue;
  8. if (options) {
  9. 'condition' in options && (this._condition = options.condition);
  10. }
  11. }
  12. _transform(chunk, encoding, callback) {
  13. if (this._condition.call(this, chunk)) {
  14. this.push(chunk);
  15. } else {
  16. this._transform = this._doNothing;
  17. }
  18. callback(null);
  19. }
  20. _doNothing(chunk, encoding, callback) {
  21. callback(null);
  22. }
  23. static make(condition) {
  24. return new TakeWhile(typeof condition == 'object' ? condition : {condition});
  25. }
  26. }
  27. TakeWhile.make.Constructor = TakeWhile;
  28. module.exports = TakeWhile.make;