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[], options: PivotOptions ): Record> { const { index, columns, values, aggFunc = arr => arr.reduce((a, b) => a + b, 0) } = options; const cellMap: Record> = {}; 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> = {}; Object.entries(cellMap).forEach(([rowKey, cols]) => { result[rowKey] = {}; Object.entries(cols).forEach(([colKey, valuesArr]) => { result[rowKey][colKey] = aggFunc(valuesArr); }); }); return result; }