fold.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. 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. callback(null);
  22. },
  23. error => callback(error)
  24. );
  25. } else {
  26. this._accumulator = result;
  27. callback(null);
  28. }
  29. }
  30. _final(callback) {
  31. this.push(this._accumulator);
  32. callback(null);
  33. }
  34. static make(reducer, initial) {
  35. return new Fold(typeof reducer == 'object' ? reducer : {reducer, initial});
  36. }
  37. }
  38. Fold.make.Constructor = Fold;
  39. module.exports = Fold.make;