takeWhile.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. const result = this._condition.call(this, chunk);
  14. if (result && typeof result.then == 'function') {
  15. result.then(
  16. flag => {
  17. if (flag) {
  18. this.push(chunk);
  19. } else {
  20. this._transform = this._doNothing;
  21. }
  22. callback(null);
  23. },
  24. error => callback(error)
  25. );
  26. } else {
  27. if (result) {
  28. this.push(chunk);
  29. } else {
  30. this._transform = this._doNothing;
  31. }
  32. callback(null);
  33. }
  34. }
  35. _doNothing(chunk, encoding, callback) {
  36. callback(null);
  37. }
  38. static make(condition) {
  39. return new TakeWhile(typeof condition == 'object' ? condition : {condition});
  40. }
  41. }
  42. TakeWhile.make.Constructor = TakeWhile;
  43. module.exports = TakeWhile.make;