Reduce.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use strict';
  2. const {Writable} = require('stream');
  3. const defaultInitial = 0;
  4. const defaultReducer = (acc, value) => value;
  5. class Reduce extends Writable {
  6. constructor(options) {
  7. super(Object.assign({}, options, {objectMode: 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. _write(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. static make(reducer, initial) {
  31. return new Reduce(typeof reducer == 'object' ? reducer : {reducer, initial});
  32. }
  33. }
  34. Reduce.reduce = Reduce.make;
  35. Reduce.make.Constructor = Reduce;
  36. module.exports = Reduce;