From 094b91c6f07fc97497018d5238d0afa33262e9d9 Mon Sep 17 00:00:00 2001 From: "(quasar) nebula" Date: Sat, 24 Feb 2024 12:58:03 -0400 Subject: data: withSortedList: build stableToUnstable iteratively --- src/data/composite/data/withSortedList.js | 33 ++++++++++++++++--------------- 1 file changed, 17 insertions(+), 16 deletions(-) (limited to 'src/data/composite') diff --git a/src/data/composite/data/withSortedList.js b/src/data/composite/data/withSortedList.js index eda050ab..fc0ed9e9 100644 --- a/src/data/composite/data/withSortedList.js +++ b/src/data/composite/data/withSortedList.js @@ -95,37 +95,38 @@ export default templateCompositeFrom({ return comparison; }); - const symbolToStable = new Map(); const stableSortIndices = []; const sortedList = []; + const symbolToStable = new Map(); + const stableToUnstable = new Map(); + for (const [stableIndex, symbol] of symbols.entries()) { const sourceIndex = symbolToIndex.get(symbol); stableSortIndices.push(sourceIndex); symbolToStable.set(symbol, stableIndex); sortedList.push(list[sourceIndex]); - } - const push = (array, value) => { - array.push(value); - return array; - }; + if (stableIndex === 0) { + stableToUnstable.set(stableIndex, 0); + continue; + } + + const previousUnstable = stableToUnstable.get(stableIndex - 1); - const stableToUnstable = - symbols.reduce( - (accumulator, current, index) => - (index === 0 - ? push(accumulator, 0) - : (isEqual(current, symbols[index - 1]) - ? push(accumulator, accumulator.at(-1)) - : push(accumulator, accumulator.at(-1) + 1))), - []); + const newUnstable = + (isEqual(symbol, symbols[stableIndex - 1]) + ? previousUnstable + : previousUnstable + 1); + + stableToUnstable.set(stableIndex, newUnstable); + } const unstableSortIndices = originalIndices .map(index => indexToSymbol.get(index)) .map(symbol => symbolToStable.get(symbol)) - .map(stable => stableToUnstable[stable]); + .map(stable => stableToUnstable.get(stable)); return continuation({ ['#sortedList']: sortedList, -- cgit 1.3.0-6-gf8a5