reconstruct
This commit is contained in:
parent
20002030ad
commit
ca8bded949
17 changed files with 1268 additions and 1110 deletions
36
services/pivot_table.ts
Normal file
36
services/pivot_table.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import { analytics } from './analytics_engine'; // Import your analytics engine
|
||||
|
||||
export interface PivotOptions {
|
||||
index: string[];
|
||||
columns: string[];
|
||||
values: string;
|
||||
aggFunc?: (items: number[]) => number; // Aggregation function (e.g., analytics.mean)
|
||||
}
|
||||
|
||||
export function pivotTable(
|
||||
data: Record<string, any>[],
|
||||
options: PivotOptions
|
||||
): Record<string, Record<string, number>> {
|
||||
const { index, columns, values, aggFunc = arr => arr.reduce((a, b) => a + b, 0) } = options;
|
||||
const cellMap: Record<string, Record<string, number[]>> = {};
|
||||
|
||||
data.forEach(row => {
|
||||
const rowKey = index.map(k => row[k]).join('|');
|
||||
const colKey = columns.map(k => row[k]).join('|');
|
||||
|
||||
if (!cellMap[rowKey]) cellMap[rowKey] = {};
|
||||
if (!cellMap[rowKey][colKey]) cellMap[rowKey][colKey] = [];
|
||||
cellMap[rowKey][colKey].push(row[values]);
|
||||
});
|
||||
|
||||
// Apply aggregation function to each cell
|
||||
const result: Record<string, Record<string, number>> = {};
|
||||
Object.entries(cellMap).forEach(([rowKey, cols]) => {
|
||||
result[rowKey] = {};
|
||||
Object.entries(cols).forEach(([colKey, valuesArr]) => {
|
||||
result[rowKey][colKey] = aggFunc(valuesArr);
|
||||
});
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue