Przeglądaj źródła

Switched from a class to a factory function, updated a test.

Eugene Lazutkin 3 lat temu
rodzic
commit
a9019660e7
2 zmienionych plików z 33 dodań i 34 usunięć
  1. 32 33
      src/utils/ReduceStream.js
  2. 1 1
      tests/test_fold.js

+ 32 - 33
src/utils/ReduceStream.js

@@ -5,40 +5,39 @@ const {Writable} = require('stream');
 const defaultInitial = 0;
 const defaultReducer = (acc, value) => value;
 
-class ReduceStream extends Writable {
-  constructor(options) {
-    super(Object.assign({}, {objectMode: true}, options));
-    this.accumulator = defaultInitial;
-    this._reducer = defaultReducer;
-    if (options) {
-      'initial' in options && (this.accumulator = options.initial);
-      'reducer' in options && (this._reducer = options.reducer);
-    }
+const reduceStream = (options, initial) => {
+  if (!options || !options.reducer) {
+    options = {reducer: options, initial};
   }
-  _write(chunk, encoding, callback) {
-    const result = this._reducer.call(this, this.accumulator, chunk);
-    if (result && typeof result.then == 'function') {
-      result.then(
-        value => {
-          this.accumulator = value;
-          callback(null);
-        },
-        error => callback(error)
-      );
-    } else {
-      this.accumulator = result;
-      callback(null);
-    }
-  }
-  static make(reducer, initial) {
-    return new ReduceStream(typeof reducer == 'object' && reducer.reducer ? reducer : {reducer, initial});
+  let accumulator = defaultInitial,
+    reducer = defaultReducer;
+  if (options) {
+    'initial' in options && (accumulator = options.initial);
+    'reducer' in options && (reducer = options.reducer);
   }
-}
-ReduceStream.reduceStream = ReduceStream.make;
-ReduceStream.make.Constructor = ReduceStream;
 
-module.exports = ReduceStream;
+  const stream = new Writable(
+    Object.assign({}, {objectMode: true}, options, {
+      write(chunk, encoding, callback) {
+        const result = reducer.call(this, this.accumulator, chunk);
+        if (result && typeof result.then == 'function') {
+          result.then(
+            value => {
+              this.accumulator = value;
+              callback(null);
+            },
+            error => callback(error)
+          );
+        } else {
+          this.accumulator = result;
+          callback(null);
+        }
+      }
+    })
+  );
+  stream.accumulator = accumulator;
+
+  return stream;
+};
 
-// to keep ESM happy:
-module.exports.reduceStream = ReduceStream.make;
-module.exports.make = ReduceStream.make;
+module.exports = reduceStream;

+ 1 - 1
tests/test_fold.js

@@ -9,7 +9,7 @@ const fromIterable = require('../src/utils/fromIterable');
 const fold = require('../src/utils/fold');
 const scan = require('../src/utils/scan');
 const reduce = require('../src/utils/reduce');
-const {reduceStream} = require('../src/utils/ReduceStream');
+const reduceStream = require('../src/utils/ReduceStream');
 
 const {asStream} = chain;