/* Copyright 2026 Marimo. All rights reserved. */ /* oxlint-disable typescript/no-explicit-any */ import { Logger } from "./Logger"; type NoInfer = [T][T extends any ? 0 : never]; export const Maps = { /** * keyBy for Map, with duplicate key detection. */ keyBy( items: Iterable, key: (item: NoInfer) => K, ): Map { const map = new Map(); const duplicateIds = new Set(); for (const item of items) { const k = key(item); if (map.has(k)) { duplicateIds.add(k); } map.set(k, item); } if (duplicateIds.size > 0) { Logger.trace(`Duplicate keys: ${[...duplicateIds].join(", ")}`); } return map; }, collect( items: Iterable, key: (item: NoInfer) => K, mapper: (item: NoInfer) => V, ): Map { return Maps.mapValues(Maps.keyBy(items, key), mapper); }, /** * Filter a map by a predicate. */ filterMap( map: Map, predicate: (value: V, key: K) => boolean, ): Map { const result = new Map(); for (const [key, value] of map) { if (predicate(value, key)) { result.set(key, value); } } return result; }, mapValues( map: Map, mapper: (value: V, key: K) => V2, ): Map { const result = new Map(); for (const [key, value] of map) { result.set(key, mapper(value, key)); } return result; }, };