scan.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict';
  2. const {Transform} = require('stream');
  3. const defaultInitial = 0;
  4. const defaultReducer = (acc, value) => value;
  5. class Scan extends Transform {
  6. constructor(options) {
  7. super(Object.assign({}, options, {writableObjectMode: true, readableObjectMode: true}));
  8. this._accumulator = defaultInitial;
  9. this._reducer = defaultReducer;
  10. if (options) {
  11. 'initial' in options && (this._accumulator = options.initial);
  12. 'reducer' in options && (this._reducer = options.reducer);
  13. }
  14. }
  15. _transform(chunk, encoding, callback) {
  16. const result = this._reducer.call(this, this._accumulator, chunk);
  17. if (result && typeof result.then == 'function') {
  18. result.then(
  19. value => {
  20. this._accumulator = value;
  21. this.push(this._accumulator);
  22. callback(null);
  23. },
  24. error => callback(error)
  25. );
  26. } else {
  27. this._accumulator = result;
  28. this.push(this._accumulator);
  29. callback(null);
  30. }
  31. }
  32. static make(reducer, initial) {
  33. return new Scan(typeof reducer == 'object' ? reducer : {reducer, initial});
  34. }
  35. }
  36. Scan.make.Constructor = Scan;
  37. module.exports = Scan.make;