diff --git a/publicodes/source/mecanisms/variations.ts b/publicodes/source/mecanisms/variations.ts index a61176c46..16478264a 100644 --- a/publicodes/source/mecanisms/variations.ts +++ b/publicodes/source/mecanisms/variations.ts @@ -63,7 +63,7 @@ export default function parseVariations(v, context): VariationNode { } } -const evaluate: EvaluationFunction<'variations'> = function (node) { +const evaluate: evaluationFunction<'variations'> = function (node) { const [temporalValue, explanation, unit] = node.explanation.reduce< [ Temporal, @@ -164,6 +164,7 @@ const evaluate: EvaluationFunction<'variations'> = function (node) { [] ) ) + return { ...node, nodeValue, diff --git a/publicodes/source/replacement.tsx b/publicodes/source/replacement.tsx index 4aef93352..21a90e786 100644 --- a/publicodes/source/replacement.tsx +++ b/publicodes/source/replacement.tsx @@ -16,8 +16,22 @@ export type ReplacementRule = { whiteListedNames: Array rawNode: any blackListedNames: Array + remplacementRuleId: number } +// Replacements depend on the context and their evaluation implies using +// "variations" node everywhere there is a reference to the original rule. +// However for performance reason we want to mutualize identical "variations" +// nodes instead of duplicating them, to avoid wasteful computations. +// +// The implementation works by first attributing an identifier for each +// replacementRule. We then use this identifier to create a cache key that +// represent the combinaison of applicables replacements for a given reference. +// For example if replacements 12, 13 et 643 are applicable we use the key +// `12-13-643` as the cache identifier in the `inlineReplacements` function. +let remplacementRuleId = 0 +const cache = {} + export function parseReplacements( replacements: Rule['remplace'], context: Context @@ -51,6 +65,7 @@ export function parseReplacements( replacementNode, whiteListedNames, blackListedNames, + remplacementRuleId: remplacementRuleId++, } as ReplacementRule }) } @@ -166,7 +181,11 @@ ${applicableReplacements.map( ) } - return { + const applicableReplacementsCacheKey = applicableReplacements + .map((n) => n.remplacementRuleId) + .join('-') + + cache[applicableReplacementsCacheKey] ??= { nodeKind: 'variations', visualisationKind: 'replacement', rawNode: node.rawNode, @@ -181,4 +200,5 @@ ${applicableReplacements.map( }, ], } + return cache[applicableReplacementsCacheKey] }