diff options
author | Tor Andersson <tor@ccxvii.net> | 2024-09-26 00:17:37 +0200 |
---|---|---|
committer | Tor Andersson <tor@ccxvii.net> | 2024-09-26 00:18:23 +0200 |
commit | c8c38a190c891185bad382e34dcc749c6683a6c4 (patch) | |
tree | 1509a08f4ab3cf276bfca6841556ee49e04e75fc | |
parent | 2146f9bfb055f890ae8f8296b5c218f039ba067e (diff) | |
download | server-c8c38a190c891185bad382e34dcc749c6683a6c4.tar.gz |
Add map_for_each and map_group_by to utility library.
-rw-r--r-- | public/common/util.js | 29 |
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 +} |