« get me outta code hell

sugar: groupArray - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
author(quasar) nebula <qznebula@protonmail.com>2024-05-06 12:29:23 -0300
committer(quasar) nebula <qznebula@protonmail.com>2024-05-31 12:11:50 -0300
commit2af0bf5b9a30abf28db68c8c3e54c48c722e6c14 (patch)
tree562a7bbcccfd76bafabb9719803d0399e39990e0 /src
parente5d214a624cb06e8985d63aa073082113f9a1901 (diff)
sugar: groupArray
Diffstat (limited to 'src')
-rw-r--r--src/util/sugar.js17
1 files changed, 17 insertions, 0 deletions
diff --git a/src/util/sugar.js b/src/util/sugar.js
index 1c057ed1..3fa3fb46 100644
--- a/src/util/sugar.js
+++ b/src/util/sugar.js
@@ -136,6 +136,23 @@ export function stitchArrays(keyToArray) {
   return results;
 }
 
+// Like Map.groupBy! Collects the items of an unsorted array into buckets
+// according to a per-item computed value.
+export function groupArray(items, fn) {
+  const buckets = new Map();
+
+  for (const [index, item] of Array.prototype.entries.call(items)) {
+    const key = fn(item, index);
+    if (buckets.has(key)) {
+      buckets.get(key).push(item);
+    } else {
+      buckets.set(key, [item]);
+    }
+  }
+
+  return buckets;
+}
+
 // Turns this:
 //
 //   [