UNPKG

als-statistics

Version:

Modular JS statistics toolkit for Node.js and the browser: descriptive stats, correlations (Pearson/Spearman/Kendall), t-tests & ANOVA (Student/Welch), reliability (Cronbach’s alpha), regression (linear/logistic), clustering (DBSCAN/HDBSCAN), and table/co

25 lines (23 loc) 1.38 kB
const n = (v) => v === undefined export class BaseStats { #sum; #mean; #v; #vS; constructor(values, name) { if (!Array.isArray(values)) throw new Error(`${name} must be array or Column instance`); this.values = values.filter(Number.isFinite); this.n = this.values.length; this.name = name; } get sum() { if (n(this.#sum)) this.#sum = this.values.reduce((t, v) => t + v, 0); return this.#sum; } get mean() { if (n(this.#mean)) this.#mean = this.n ? this.sum / this.n : NaN; return this.#mean; } get variance() { if (n(this.#v)) this.#v = this.n ? this.values.reduce((t, v) => t + (v - this.mean) ** 2, 0) / this.n : NaN; return this.#v; } get stdDev() { return Math.sqrt(this.variance); } get varianceSample() { if (n(this.#vS)) this.#vS = (this.n < 2) ? NaN : this.values.reduce((t, v) => t + (v - this.mean) ** 2, 0) / (this.n - 1); return this.#vS; } get stdDevSample() { return Math.sqrt(this.varianceSample); } get weight() { return this.varianceSample > 0 ? this.n / this.varianceSample : 0; } } export function stats(vs, name, options = {}) { const { min } = options; const s = (vs && vs.constructor && vs.constructor.name === 'Column' || vs instanceof BaseStats) ? vs : new BaseStats(vs, name); if (min && s.n < min) throw new Error(`${name} length should be minimum ${min}, got ${s.n}`); return s; }