summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTor Andersson <tor@ccxvii.net>2024-09-26 00:17:37 +0200
committerTor Andersson <tor@ccxvii.net>2024-09-26 00:18:23 +0200
commitc8c38a190c891185bad382e34dcc749c6683a6c4 (patch)
tree1509a08f4ab3cf276bfca6841556ee49e04e75fc
parent2146f9bfb055f890ae8f8296b5c218f039ba067e (diff)
downloadserver-c8c38a190c891185bad382e34dcc749c6683a6c4.tar.gz
Add map_for_each and map_group_by to utility library.
-rw-r--r--public/common/util.js29
1 files changed, 29 insertions, 0 deletions
diff --git a/public/common/util.js b/public/common/util.js
index c14d406..7f5459e 100644
--- a/public/common/util.js
+++ b/public/common/util.js
@@ -279,6 +279,11 @@ function map_delete(map, key) {
}
}
+function map_for_each(map, f) {
+ for (let i = 0; i < map.length; i += 2)
+ f(map[i], map[i+1])
+}
+
function object_diff(a, b) {
if (a === b)
return false
@@ -327,3 +332,27 @@ function object_group_by(items, callback) {
}
return groups
}
+
+function map_group_by(items, callback) {
+ let groups = []
+ if (typeof callback === "function") {
+ for (let item of items) {
+ let key = callback(item)
+ let arr = map_get(groups, key)
+ if (arr)
+ arr.push(item)
+ else
+ map_set(groups, key, [ item ])
+ }
+ } else {
+ for (let item of items) {
+ let key = item[callback]
+ let arr = map_get(groups, key)
+ if (arr)
+ arr.push(item)
+ else
+ map_set(groups, key, [ item ])
+ }
+ }
+ return groups
+}