als-statistics
Version:
A powerful and lightweight JavaScript library for descriptive statistics, regression, clustering, outlier detection, and noise analysis using a flexible table/column architecture.
39 lines (33 loc) • 1.45 kB
JavaScript
const ColumnFilter = require('../table/filter')
const getType = require('../utils/get-type')
class BaseColumn {
cache = {};
constructor(values=[], columnFilter, type) {
if (!Array.isArray(values)) throw new Error("Input must be a non-empty array");
this.columnFilter = columnFilter || new ColumnFilter()
this.type = type || getType(values)
this._values = values;
}
count(fn,filtered=true) { return (filtered ? this.values : this._values).filter(fn) }
cached(name, fn) {
const state = this.columnFilter.filterState;
if (this.cache[name] && this.cache[name].state === state) return this.cache[name].value;
this.cache[name] = { state, value: fn() };
return this.cache[name].value;
}
filterRows(indexes) { this.columnFilter.filterRows(indexes) }
clearRowsFilters(indexes) { this.columnFilter.clearRowsFilters(indexes) }
clearAllRowsFilters() { this.columnFilter.clearAllRowsFilters() }
filterRowsBy(fn) {
const indexes = this._values.map((v, i) => fn(v, i) ? i : false).filter(v => v !== false)
this.filterRows(indexes)
}
get values() {
return this.cached('values', () => {
if (!this.columnFilter.isFiltered) return this._values
return this._values.filter((v, i) => !this.columnFilter.filtered[i])
})
}
get n() { return this.values.length }
}
module.exports = BaseColumn