scan.js 856 B

123456789101112131415161718192021222324252627
  1. const {Transform} = require('stream');
  2. const defaultInitial = 0;
  3. const defaultReducer = (acc, value) => value;
  4. class Scan extends Transform {
  5. constructor(options) {
  6. super(Object.assign({}, options, {writableObjectMode: true, readableObjectMode: true}));
  7. this._accumulator = defaultInitial;
  8. this._reducer = defaultReducer;
  9. if (options) {
  10. 'initial' in options && (this._accumulator = options.initial);
  11. 'reducer' in options && (this._reducer = options.reducer);
  12. }
  13. }
  14. _transform(chunk, encoding, callback) {
  15. this._accumulator = this._reducer.call(this, this._accumulator, chunk);
  16. this.push(this._accumulator);
  17. callback(null);
  18. }
  19. static make(reducer, initial) {
  20. return new Scan(typeof reducer == 'object' ? reducer : {reducer, initial});
  21. }
  22. }
  23. Scan.make.Constructor = Scan;
  24. module.exports = Scan.make;