rreduceStream.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. const {Writable} = require('stream');
  3. const defaultInitial = 0;
  4. const defaultReducer = (acc, value) => value;
  5. const reduceStream = (options, initial) => {
  6. if (!options || !options.reducer) {
  7. options = {reducer: options, initial};
  8. }
  9. let accumulator = defaultInitial,
  10. reducer = defaultReducer;
  11. if (options) {
  12. 'initial' in options && (accumulator = options.initial);
  13. 'reducer' in options && (reducer = options.reducer);
  14. }
  15. const stream = new Writable(
  16. Object.assign({}, {objectMode: true}, options, {
  17. write(chunk, encoding, callback) {
  18. const result = reducer.call(this, this.accumulator, chunk);
  19. if (result && typeof result.then == 'function') {
  20. result.then(
  21. value => {
  22. this.accumulator = value;
  23. callback(null);
  24. },
  25. error => callback(error)
  26. );
  27. } else {
  28. this.accumulator = result;
  29. callback(null);
  30. }
  31. }
  32. })
  33. );
  34. stream.accumulator = accumulator;
  35. return stream;
  36. };
  37. module.exports = reduceStream;