UNPKG

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.

73 lines (68 loc) 2.98 kB
const ColumnFilter = require('./filter') const compute = require('./compute') const extractMetrics = require('./extract-metric') const transpose = require('./transpose') const newColumn = require('../utils/new-column') const filterColumns = require('./filter-columns') const addRow = require('./add-row') const { Comparative, CronbachAlpha, Dbscan, Hdbscan, LinearRegression } = require('./instruments/index') class Table extends ColumnFilter { constructor(data) { super() this.n = 0; this.columns = {} this.columnsN = 0 if(data && typeof data === 'object' && !Array.isArray(data) && data !== null) { for (let colName in data) this.addColumn(colName, data[colName]) } } get Table() { return Table } get cronbachAlpha() { return new CronbachAlpha(this) } addRow(obj, index) { return addRow(obj, index, this) } deleteColumn(name) { if (!this.columns[name]) return; this.columns[name].columnFilter = new ColumnFilter(); delete this.columns[name]; const colValues = Object.values(this.columns) this.columnsN = colValues.length this.n = Math.max(...colValues.map(col => col.n), 0); return this } addColumn(name, values = []) { this.columns[name] = values.constructor.name.includes('Column') ? values : newColumn(values, this) if (this.columns[name].n > this.n) this.n = this.columns[name].n this.columnsN++ return this.columns[name] } filterRowsBy(colName, fn) { if (this.columns[colName]) this.columns[colName].filterRowsBy(fn); return this } clone(filtered = true, columnFilter = null) { const table = new Table(); const filteredNames = filterColumns(this.columns, columnFilter); for (let columnName of filteredNames) { if (!this.columns[columnName]) continue table.addColumn(columnName, this.columns[columnName].clone(filtered, table)); } return table; } compare(colName1, colName2) { return new Comparative(this.columns[colName1], this.columns[colName2]) } transpose() { return transpose(new Table(), this) } descriptive(metricName, table) { return newColumn(extractMetrics(this.columns, metricName), table) } compute(fn, targetName) { return targetName ? this.addColumn(targetName, compute(fn, this)) : newColumn(compute(fn, this)) } where(fn) { return compute((obj, i) => {if(!this.filtered[i] && fn(obj, i)) return i }, this).filter((v) => v !== undefined) } dbscan(eps = 0.4, minPts = 3) { return new Dbscan(this, eps, minPts) } hdbscan(minPts = 3) { return new Hdbscan(this, minPts) } linearRegression(yName, xNames) { return new LinearRegression(this,yName,xNames) } get json() { const obj = {} for(const colName in this.columns) { obj[colName] = this.columns[colName].values } return obj } } module.exports = Table