« get me outta code hell

data: withSortedList: build stableToUnstable iteratively - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data
diff options
context:
space:
mode:
author(quasar) nebula <qznebula@protonmail.com>2024-02-24 12:58:03 -0400
committer(quasar) nebula <qznebula@protonmail.com>2024-02-24 13:35:53 -0400
commit094b91c6f07fc97497018d5238d0afa33262e9d9 (patch)
tree86eba2f364c29ed39e024b4e21f0fe83ce312c85 /src/data
parent6c2fee0ec06693d442dfdac3afd5a9a8fe6704b3 (diff)
data: withSortedList: build stableToUnstable iteratively
Diffstat (limited to 'src/data')
-rw-r--r--src/data/composite/data/withSortedList.js33
1 files changed, 17 insertions, 16 deletions
diff --git a/src/data/composite/data/withSortedList.js b/src/data/composite/data/withSortedList.js
index eda050a..fc0ed9e 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,