One-liners#
Single-expression idioms for the REPL.
Dedupe an array while preserving order.
const uniq = [...new Set(xs)];
Flatten one level.
const flat = xs.flat();
Group by a key into an object.
const groups = xs.reduce((m, x) => ((m[x.k] ??= []).push(x), m), {});
Build a dict from two parallel arrays.
const d = Object.fromEntries(keys.map((k, i) => [k, values[i]]));
Invert an object (values become keys).
const inv = Object.fromEntries(Object.entries(o).map(([k, v]) => [v, k]));
Count occurrences.
const c = xs.reduce((m, x) => (m[x] = (m[x] ?? 0) + 1, m), {});
Sleep N milliseconds.
await new Promise(r => setTimeout(r, 1000));
Race a promise against a timeout.
const r = await Promise.race([p, new Promise((_, j) => setTimeout(() => j("timeout"), 2000))]);
Parse a URL.
const u = new URL("https://example.com:8443/p?x=1#f");
Fetch JSON.
const data = await fetch(url).then(r => r.json());
Encode and decode base64.
btoa("hello"); atob("aGVsbG8=");