@codibre/fluent-iterable
Version:
Provides LINQ-like fluent api operations for iterables and async iterables (ES2018+).
81 lines (80 loc) • 2.38 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMinMaxStepper = getMinMaxStepper;
exports.getStatsStepper = getStatsStepper;
const utils_1 = require("./utils");
const fluent_1 = __importDefault(require("../fluent"));
const SQUARE = 2;
function getMinMaxStepper() {
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
const wrapper = {
get min() {
return min;
},
get max() {
return max;
},
step(y) {
if (min > y)
min = y;
if (max < y)
max = y;
return y;
},
};
return wrapper;
}
/**
* Stepper to calculate many statistical measures, like
* min, max, population standard deviation, population variance,
* sample standard deviation and sample variance
*/
function getStatsStepper() {
const avgStepper = (0, utils_1.getAverageStepper)();
const minMaxStepper = getMinMaxStepper();
let variance;
let lastVarianceCount = 0;
const items = [];
const wrapper = {
get avg() {
return avgStepper.avg;
},
get count() {
return avgStepper.count;
},
get min() {
return minMaxStepper.min;
},
get max() {
return minMaxStepper.max;
},
get populationVariance() {
if (variance === undefined || lastVarianceCount !== avgStepper.count) {
variance = (0, fluent_1.default)(items)
.map((x) => (x - avgStepper.avg) ** SQUARE)
.avg();
lastVarianceCount = avgStepper.count;
}
return variance;
},
get populationStdDev() {
return Math.sqrt(this.populationVariance);
},
get sampleVariance() {
return ((this.populationVariance * avgStepper.count) / (avgStepper.count - 1));
},
get sampleStdDev() {
return Math.sqrt(this.sampleVariance);
},
step: (y) => {
items.push(y);
avgStepper.step(y);
return minMaxStepper.step(y);
},
};
return wrapper;
}