| 9 | * Formulas reference event series using alphabet IDs (A, B, C, etc.) |
| 10 | */ |
| 11 | export function compute( |
| 12 | fetchedSeries: ConcreteSeries[], |
| 13 | definitions: Array<{ |
| 14 | type: 'event' | 'formula'; |
| 15 | id?: string; |
| 16 | formula?: string; |
| 17 | }>, |
| 18 | ): ConcreteSeries[] { |
| 19 | const results: ConcreteSeries[] = [...fetchedSeries]; |
| 20 | |
| 21 | // Process formulas in order (they can reference previous formulas) |
| 22 | definitions.forEach((definition, formulaIndex) => { |
| 23 | if (definition.type !== 'formula') { |
| 24 | return; |
| 25 | } |
| 26 | |
| 27 | const formula = definition as IChartFormula; |
| 28 | if (!formula.formula) { |
| 29 | return; |
| 30 | } |
| 31 | |
| 32 | // Group ALL series (events + previously computed formulas) by breakdown signature |
| 33 | // Series with the same breakdown values should be computed together |
| 34 | const seriesByBreakdown = new Map<string, ConcreteSeries[]>(); |
| 35 | |
| 36 | // Include both fetched event series AND previously computed formulas |
| 37 | const allSeries = [ |
| 38 | ...fetchedSeries, |
| 39 | ...results.filter((s) => s.definitionIndex < formulaIndex), |
| 40 | ]; |
| 41 | |
| 42 | allSeries.forEach((serie) => { |
| 43 | // Create breakdown signature: skip first name part (event/formula name) and use breakdown values |
| 44 | // If name.length === 1, it means no breakdowns (just event name) |
| 45 | // If name.length > 1, name[0] is event name, name[1+] are breakdown values |
| 46 | const breakdownSignature = |
| 47 | serie.name.length > 1 ? serie.name.slice(1).join(':::') : ''; |
| 48 | |
| 49 | if (!seriesByBreakdown.has(breakdownSignature)) { |
| 50 | seriesByBreakdown.set(breakdownSignature, []); |
| 51 | } |
| 52 | seriesByBreakdown.get(breakdownSignature)!.push(serie); |
| 53 | }); |
| 54 | |
| 55 | // Compute formula for each breakdown group |
| 56 | for (const [breakdownSignature, breakdownSeries] of seriesByBreakdown) { |
| 57 | // Map series by their definition index for formula evaluation |
| 58 | const seriesByIndex = new Map<number, ConcreteSeries>(); |
| 59 | breakdownSeries.forEach((serie) => { |
| 60 | seriesByIndex.set(serie.definitionIndex, serie); |
| 61 | }); |
| 62 | |
| 63 | // Get all unique dates across all series in this breakdown group |
| 64 | const allDates = new Set<string>(); |
| 65 | breakdownSeries.forEach((serie) => { |
| 66 | serie.data.forEach((item) => { |
| 67 | allDates.add(item.date); |
| 68 | }); |