takeWhile.js 811 B

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