@jdfwarrior/defaultmap
v0.1.0
Published
A typesafe Map that returns a default value for missing keys
Maintainers
Readme
defaultmap
A typesafe TypeScript Map that returns a default value when accessing a key that doesn't exist.
Install
bun add defaultmap
# or
npm install defaultmapUsage
import DefaultMap from "defaultmap";
// Static default
const counts = new DefaultMap<string, number>(0);
counts.get("missing"); // 0
counts.get("missing"); // 0 — same value, key is now stored
// Factory default — called once per key, result is stored
const lists = new DefaultMap<string, string[]>(() => []);
lists.get("fruits").push("apple");
lists.get("fruits"); // ["apple"]
lists.get("veggies"); // [] — independent array
// Initial entries
const scores = new DefaultMap<string, number>(0, [
["alice", 10],
["bob", 20],
]);
scores.get("alice"); // 10
scores.get("charlie"); // 0API
new DefaultMap<K, V>(defaultValue: V | ((key: K) => V), entries?)
defaultValue— a static value returned for every missing key, or a factory function that receives the missing key and returns the default. The factory result is stored, so the factory is called at most once per key.entries— optional initial[key, value]pairs, same as theMapconstructor.
Note: If you pass an object/array as a static default, all missing keys share the same reference. Use a factory (
() => []) to get independent instances per key.
get(key: K): V
Returns the value for key. If the key is not present, computes and stores the default, then returns it. All other Map methods (set, delete, has, clear, forEach, keys, values, entries) behave exactly as on a standard Map.
License
MIT
