Browse packages

Package · v0.14.0 · changelog

dict

Standard library dictionaries

Runtime support

  • Node
  • Deno
  • Bun
  • Browser

This module provides typed utilities for transforming, filtering, inflating, and querying JavaScript dictionaries.

Installation#

bash
npm install @rcompat/dict
bash
pnpm add @rcompat/dict
bash
yarn add @rcompat/dict
bash
bun add @rcompat/dict

Usage#

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({}); // true

Filtering 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 } }

dict.inflate accepts dot-separated paths only. When migrating a custom separator, normalize the path first:

js
const path = "server/tls".replaceAll("/", ".");
dict.inflate(path, { enabled: true });
// { server: { tls: { enabled: true } } }

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); // true

Query strings#

js
dict.toQueryString({ page: "1", sort: "name" });
// "page=1&sort=name"

toQueryString joins string keys and values without URL-encoding them.

Runtime compatibility#

Runtime Supported
Node.js Yes
Bun Yes
Deno Yes
Browser Yes

License#

MIT

Contributing#

See CONTRIBUTING.md in the repository root.