data-collectors
Version:
A collection of composable reduction operations for arbitrary streams of values
39 lines • 1.42 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const collector_1 = require("../collector");
function averaging() {
return collector_1.Collector.of(() => ({ sum: 0, count: 0 }), (state, item) => {
state.sum += item;
state.count += 1;
}, (stateA, stateB) => ({ sum: stateA.sum + stateB.sum, count: stateA.count + stateB.count }), ({ sum, count }) => count > 0 ? sum / count : count);
}
exports.averaging = averaging;
function sum() {
return collector_1.Collector.of(() => 0, (state, item) => state + item, (stateA, stateB) => stateA + stateB, (state) => state);
}
exports.sum = sum;
function bounds(comparator) {
if (!comparator)
comparator = (a, b) => a - b;
const accumulator = (state, item) => {
if (state[0] == null || comparator(state[0], item) < 0)
state[0] = item;
if (state[1] == null || comparator(state[1], item) > 0)
state[1] = item;
};
return collector_1.Collector.of(() => [null, null], accumulator, (a, b) => {
accumulator(a, b[0]);
accumulator(a, b[1]);
return a;
});
}
exports.bounds = bounds;
function max(comparator) {
return bounds(comparator).then(b => b[1]);
}
exports.max = max;
function min(comparator) {
return bounds(comparator).then(b => b[0]);
}
exports.min = min;
//# sourceMappingURL=math.js.map