36 lines
No EOL
1.2 KiB
TypeScript
36 lines
No EOL
1.2 KiB
TypeScript
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;
|
|
} |