skipWhile.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. const {Transform} = require('stream');
  3. const alwaysFalse = () => false;
  4. class SkipWhile extends Transform {
  5. constructor(options) {
  6. super(Object.assign({}, options, {writableObjectMode: true, readableObjectMode: true}));
  7. this._condition = alwaysFalse;
  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._transform = this._passThrough;
  19. this.push(chunk);
  20. }
  21. callback(null);
  22. },
  23. error => callback(error)
  24. );
  25. } else {
  26. if (!result) {
  27. this._transform = this._passThrough;
  28. this.push(chunk);
  29. }
  30. callback(null);
  31. }
  32. }
  33. _passThrough(chunk, encoding, callback) {
  34. this.push(chunk);
  35. callback(null);
  36. }
  37. static make(condition) {
  38. return new SkipWhile(typeof condition == 'object' ? condition : {condition});
  39. }
  40. }
  41. SkipWhile.make.Constructor = SkipWhile;
  42. module.exports = SkipWhile.make;