Typed dictionary utilities for JavaScript runtimes.
Installation#
bash
npm install @rcompat/dictbash
pnpm add @rcompat/dictbash
yarn add @rcompat/dictbash
bun add @rcompat/dictUsage#
js
import dict from "@rcompat/dict";
const values = { a: 1, b: 2, c: 3 };
dict.keys(values); // ["a", "b", "c"]
dict.values(values); // [1, 2, 3]
dict.entries(values); // [["a", 1], ["b", 2], ["c", 3]]
dict.has(values, "b"); // true
dict.empty({}); // trueFiltering and mapping#
Callbacks receive the key followed by the value.
js
const values = { a: 1, b: 2, c: 3 };
dict.filter(values, (_, value) => value > 1);
// { b: 2, c: 3 }
dict.exclude(values, ["b"]);
// { a: 1, c: 3 }
dict.map(values, (_, value) => value * 10);
// { a: 10, b: 20, c: 30 }
dict.mapKey(values, key => key.toUpperCase());
// { A: 1, B: 2, C: 3 }
dict.flatMap(values, (key, value) =>
value % 2 === 0 ? [key, value * 10] : []
);
// { b: 20 }Nested dictionaries#
js
const config = {
server: {
host: "localhost",
port: 3000,
},
};
dict.get(config, "server.port"); // 3000
dict.inflate("server.tls", { enabled: true });
// { server: { tls: { enabled: true } } }
dict.override(config, { server: { port: 8080 } });
// { server: { host: "localhost", port: 8080 } }override recursively merges dictionary values. Other values from the second
dictionary replace values from the first.
Frozen dictionaries#
dict.new creates a frozen dictionary with a null prototype.
js
const config = dict.new({ mode: "production" });
Object.getPrototypeOf(config); // null
Object.isFrozen(config); // trueQuery strings#
js
dict.toQueryString({ page: "1", sort: "name" });
// "page=1&sort=name"toQueryString joins string keys and values without URL-encoding them.
API reference#
dict.empty(value)reports whether a dictionary has no own enumerable keys.dict.entries(value)returns typed[key, value]entries.dict.exclude(value, keys)returns a copy without the selected keys.dict.filter(value, predicate)keeps entries accepted by the predicate.dict.flatMap(value, mapper)maps entries and drops those mapped to[].dict.get(value, path)reads a dot-separated nested path.dict.has(value, key)checks for an own property and narrows the key type.dict.inflate(path, initial?, separator?)creates a nested dictionary.dict.keys(value)returns typed keys.dict.map(value, mapper)maps values while retaining keys.dict.mapKey(value, mapper)maps keys while retaining values.dict.new(value)creates a frozen, null-prototype dictionary.dict.override(base, over)recursively overlays two dictionaries.dict.toQueryString(value)joins entries askey=valuepairs.dict.values(value)returns typed values.
Runtime compatibility#
| Runtime | Supported |
|---|---|
| Node.js | Yes |
| Bun | Yes |
| Deno | Yes |
License#
MIT
Contributing#
See CONTRIBUTING.md in the repository root.