fold.js 916 B

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