https://project.mdnd-it.cc/work_packages/94
This commit is contained in:
2025-08-23 04:25:28 +02:00
parent 725516ad6c
commit 19cfa031d0
25823 changed files with 1095587 additions and 2801760 deletions
+40
View File
@@ -0,0 +1,40 @@
'use strict';
const {Writable} = require('stream');
const defaultInitial = 0;
const defaultReducer = (acc, value) => value;
class Reduce extends Writable {
constructor(options) {
super(Object.assign({}, options, {objectMode: true}));
this.accumulator = defaultInitial;
this._reducer = defaultReducer;
if (options) {
'initial' in options && (this.accumulator = options.initial);
'reducer' in options && (this._reducer = options.reducer);
}
}
_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 Reduce(typeof reducer == 'object' ? reducer : {reducer, initial});
}
}
Reduce.reduce = Reduce.make;
Reduce.make.Constructor = Reduce;
module.exports = Reduce;