From c8c38a190c891185bad382e34dcc749c6683a6c4 Mon Sep 17 00:00:00 2001 From: Tor Andersson Date: Thu, 26 Sep 2024 00:17:37 +0200 Subject: Add map_for_each and map_group_by to utility library. --- public/common/util.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) 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 +} -- cgit v1.2.3