fold.js 901 B

123456789101112131415161718192021222324252627282930
  1. const {Transform} = require('stream');
  2. const defaultInitial = 0;
  3. const defaultReducer = (acc, value) => value;
  4. class Fold 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. callback(null);
  17. }
  18. _final(callback) {
  19. this.push(this._accumulator);
  20. callback(null);
  21. }
  22. static make(reducer, initial) {
  23. return new Fold(typeof reducer == 'object' ? reducer : {reducer, initial});
  24. }
  25. }
  26. Fold.make.Constructor = Fold;
  27. module.exports = Fold.make;