Polyfills and JavaScript Utility Implementation Questions
Rebuilding standard JavaScript behavior and common utility libraries from scratch, the machine-coding interview genre where a candidate re-creates a familiar API to prove they understand its mechanics. Covers a minimal Promise built from first principles (chaining, asynchronous handlers, single settlement, thenable adoption, error flow) and Promise.allSettled-style combinators; polyfills for browser APIs such as IntersectionObserver, and a keyed virtual DOM diff; utilities such as debounce (leading and trailing, cancel, flush), throttle, and React hooks that debounce a value or a callback with stable identity and no stale closures; deep clone (cycles, shared references, Dates, RegExps), shallow and deep equality (typed arrays, Maps and Sets, NaN and -0), nested object helpers (safe path get, flatten and unflatten, deep merge), curry with placeholders and partial application, and memoize with cache keys and WeakMap-based caches; and small infrastructure such as event emitters (on, off, once, emit, context binding, listener leaks). Emphasizes edge cases, correct this binding, argument handling, spec fidelity, and complexity. Using these built-ins as a language feature, the event loop and async/await semantics, DOM traversal and event propagation, functional programming as a paradigm, and generic algorithm puzzles are covered elsewhere.
Implement flatten and its inverse unflatten for nested objects with dotted keys, where arrays use indexed keys. Inputs must not be mutated and empty objects must survive the round trip.
Sample Answer
Direct answer
flatten walks the nested object and writes each leaf under a path string such as items[0].opts.on; unflatten parses each path back into steps and rebuilds the containers. The round trip is only lossless if the path format answers three questions without guessing: is this step an array index or an object key, what stands for an empty object or array, and what if a key itself contains . or [? The design below answers them with bracket notation for array indices (tags[1]), empty containers stored as leaf values (empty: {}), and backslash escapes for ., [, ] and \ inside keys.
Why a.0 style array keys are not enough
If arrays and objects both use dotted keys, {numeric: ['a', 'b']} and {numeric: {0: 'a', 1: 'b'}} flatten to the identical numeric.0, numeric.1. The unflatten step can then only guess ("digits mean array"), and a guess is wrong for one of the two inputs. Bracket indices make the shape explicit: numeric[0] is an array, numeric.0 is an object key '0'. The run shows the guessing version rebuilding an array from the object's keys (dotted-index round trip is an array: true) while the bracket format keeps the object an object (false).
Implementation
import assert from 'node:assert/strict';
const isPlain = (v) => Object.prototype.toString.call(v) === '[object Object]';
const escapeKey = (k) => k.replace(/[\\.[\]]/g, '\\$&');
function flatten(obj) {
if (!isPlain(obj)) throw new TypeError('flatten: expected a plain object');
const out = {};
const ancestors = new Set();
const walk = (value, path, isRoot = false) => {
const container = Array.isArray(value) ? 'array' : isPlain(value) ? 'object' : null;
if (container === null) { setOwn(out, path, value); return; }
if (Object.keys(value).length === 0 && !isRoot) { setOwn(out, path, container === 'array' ? [] : {}); return; }
if (ancestors.has(value)) throw new TypeError('flatten: circular reference');
ancestors.add(value);
if (container === 'array') value.forEach((item, i) => walk(item, `${path}[${i}]`));
else for (const k of Object.keys(value)) walk(value[k], isRoot ? escapeKey(k) : `${path}.${escapeKey(k)}`);
ancestors.delete(value);
};
walk(obj, '', true);
return out;
}
// the path text a[0].b\.c -> ['a', 0, 'b.c'] (numbers are array indices, strings are object keys)
function parsePath(path) {
const steps = [];
let i = 0;
for (;;) {
let key = '';
while (i < path.length && path[i] !== '.' && path[i] !== '[') {
if (path[i] === '\\') i++;
key += path[i++];
}
steps.push(key);
while (path[i] === '[') {
const end = path.indexOf(']', i);
steps.push(Number(path.slice(i + 1, end)));
i = end + 1;
}
if (path[i] === '.') i++; else break;
}
return steps;
}
function setOwn(target, key, value) {
Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
}
function unflatten(flat) {
const root = {};
for (const [path, leaf] of Object.entries(flat)) {
const steps = parsePath(path);
let node = root;
steps.forEach((step, n) => {
const last = n === steps.length - 1;
if (last) {
if (Object.hasOwn(node, step)) throw new Error(`unflatten: conflict at "${path}"`);
const isEmptyBox = (Array.isArray(leaf) || isPlain(leaf)) && Object.keys(leaf).length === 0;
setOwn(node, step, isEmptyBox ? (Array.isArray(leaf) ? [] : {}) : leaf);
return;
}
let next = Object.hasOwn(node, step) ? node[step] : undefined;
if (next === undefined) {
next = typeof steps[n + 1] === 'number' ? [] : {};
setOwn(node, step, next);
} else if (typeof next !== 'object' || next === null || Array.isArray(next) !== (typeof steps[n + 1] === 'number')) {
throw new Error(`unflatten: conflict at "${path}"`);
}
node = next;
});
}
return root;
}
// --- harness ---
const sample = {
name: 'Ada',
tags: ['x', ['y', 'z']],
items: [{ id: 1, opts: {} }, { id: 2, opts: { on: true } }],
empty: {},
none: [],
nothing: null,
missing: undefined,
'a.b': { 'c[0]': 'odd keys', 'back\\slash': 1 },
'': 'empty key',
numeric: { 0: 'object, not array', 1: 'second' },
};
const flat = flatten(sample);
console.log(flat);
const back = unflatten(flat);
assert.deepStrictEqual(back, sample);
assert.ok(Array.isArray(back.tags) && !Array.isArray(back.numeric));
assert.notEqual(back.empty, sample.empty);
assert.notEqual(back.empty, flat.empty); // unflatten builds its own empty containers
assert.notEqual(back.none, flat.none);
// one object reachable from two keys is not a cycle: the ancestor set is emptied on the way up
const shared = { x: 1 };
assert.deepStrictEqual(flatten({ a: shared, b: shared }), { 'a.x': 1, 'b.x': 1 });
// the dotted-index format cannot tell an object with numeric keys from an array
function naiveUnflatten(flatMap) {
const root = {};
for (const [p, v] of Object.entries(flatMap)) {
const parts = p.split('.');
parts.reduce((node, key, i) => {
if (i === parts.length - 1) { node[key] = v; return node; }
return (node[key] ??= /^\d+$/.test(parts[i + 1]) ? [] : {});
}, root);
}
return root;
}
const asObject = { numeric: { 0: 'a', 1: 'b' } };
const dotted = { 'numeric.0': 'a', 'numeric.1': 'b' }; // what a dotted-index flatten gives
console.log('dotted-index round trip is an array:', Array.isArray(naiveUnflatten(dotted).numeric));
console.log('bracket round trip is an array:', Array.isArray(unflatten(flatten(asObject)).numeric));
// input is not mutated
const frozen = JSON.parse(JSON.stringify(sample));
const snapshot = structuredClone(frozen);
flatten(frozen); unflatten(flatten(frozen));
assert.deepStrictEqual(frozen, snapshot);
const flatIn = Object.freeze({ 'a.b': 1, 'a.c': 2 });
const copy = { ...flatIn };
unflatten(flatIn);
assert.deepStrictEqual(flatIn, copy);
// an empty-string key is a real key, not the root
const tricky = { '': { x: 1 }, x: 2, y: { '': [1] } };
assert.deepStrictEqual(flatten(tricky), { '.x': 1, x: 2, 'y.[0]': 1 });
assert.deepStrictEqual(unflatten(flatten(tricky)), tricky);
assert.deepStrictEqual(unflatten(flatten({ '': {} })), { '': {} });
// conflicts and hostile keys
assert.throws(() => unflatten({ a: 1, 'a.b': 2 }), /conflict/);
assert.throws(() => unflatten({ 'a.b': 1, a: 2 }), /conflict/);
unflatten({ '__proto__.polluted': 'yes' });
assert.equal(({}).polluted, undefined);
console.log('Object.prototype polluted:', ({}).polluted !== undefined);
// seeded random round trips
let seed = 12345;
const rnd = () => (seed = (seed * 1664525 + 1013904223) >>> 0) / 2 ** 32;
const keyPool = ['a', 'b', 'a.b', 'c[0]', '0', '', 'x\\y', '__proto__'];
const make = (depth) => {
const r = rnd();
if (depth === 0 || r < 0.3) return [1, 'two', null, true, undefined][Math.floor(rnd() * 5)];
if (r < 0.65) return Array.from({ length: Math.floor(rnd() * 3) }, () => make(depth - 1));
const o = {};
for (let n = Math.floor(rnd() * 3); n > 0; n--) setOwn(o, keyPool[Math.floor(rnd() * keyPool.length)], make(depth - 1));
return o;
};
let ok = 0;
for (let n = 0; n < 500; n++) {
const o = {}; setOwn(o, keyPool[Math.floor(rnd() * keyPool.length)], make(4));
assert.deepStrictEqual(unflatten(flatten(o)), o);
ok++;
}
console.log(`random round trips equal: ${ok} of 500`);
Run in a node:22 container, it prints:
{
name: 'Ada',
'tags[0]': 'x',
'tags[1][0]': 'y',
'tags[1][1]': 'z',
'items[0].id': 1,
'items[0].opts': {},
'items[1].id': 2,
'items[1].opts.on': true,
empty: {},
none: [],
nothing: null,
missing: undefined,
'a\\.b.c\\[0\\]': 'odd keys',
'a\\.b.back\\\\slash': 1,
'': 'empty key',
'numeric.0': 'object, not array',
'numeric.1': 'second'
}
dotted-index round trip is an array: true
bracket round trip is an array: false
Object.prototype polluted: false
random round trips equal: 500 of 500
The printed keys use JavaScript's display escaping: the key shown as 'a\\.b.c\\[0\\]' is the 11-character text a\.b.c\[0\] with single backslashes, which is the key a.b joined to the key c[0] with a real dot. The display doubles each backslash.
Every assert throws on failure. The flat listing shows the ten top-level properties of sample (including none: [], missing: undefined, the empty-string key and the keys a.b, c[0] and back\slash) coming back identical under assert.deepStrictEqual. The final line is a seeded generator producing 500 random nested structures with awkward keys; all 500 survive unflatten(flatten(x)). A linear congruential generator is a tiny pseudo-random number generator (next = (a * previous + c) mod 2^32); starting it from the fixed seed 12345 makes the same 500 structures appear on every run, and 500 passes is enough to hit combinations of empty containers, nested arrays and keys like a.b, c[0], '' and __proto__ that a hand-written list would miss. A round trip means unflatten(flatten(x)) must give back something deep-equal to x. The structuredClone snapshot in the immutability test is an independent deep copy taken before the calls, so comparing against it afterwards proves the input was not modified.
Tracing parsePath
The path text a[0].b\.c (written 'a[0].b\\.c' inside a JavaScript string, because the string literal needs two backslashes to hold one) has 9 characters: a, [, 0, ], ., b, \, ., c. parsePath reads it in these steps:
| Step | Position i | What the code does | steps afterwards |
|---|---|---|---|
| 1 | 0 to 1 | The inner while collects a and stops at [ | ['a'] |
| 2 | 1 to 4 | path[i] === '[': indexOf(']') is 3, so Number('0') is pushed and i moves to 4 | ['a', 0] |
| 3 | 4 to 5 | path[4] is ., so skip it and loop again | ['a', 0] |
| 4 | 5 to 9 | Collect b. At the backslash (position 6) i++ skips it, so . at position 7 is added as ordinary text, not as a separator. Then c. The key b.c is pushed | ['a', 0, 'b.c'] |
| 5 | 9 | path[9] is neither [ nor ., so the loop breaks | ['a', 0, 'b.c'] |
How each requirement is met
| Requirement | Mechanism |
|---|---|
| Arrays use indexed keys | items[0].id, nested tags[1][0] |
| Inputs are not mutated | Both functions only read their input and build new containers. The tests run them on a deep copy and compare against a structuredClone snapshot, and unflatten a frozen flat object |
| Empty objects survive | An empty object or array is written as a leaf (empty: {}, none: []); unflatten recognises an empty-container leaf and creates a fresh empty one instead of sharing the flat object's (the test asserts back.empty !== flat.empty, and swapping in setOwn(node, step, leaf) makes it fail) |
Keys with ., [, ] or \ | escapeKey prefixes each with a backslash, and parsePath removes the backslash while reading |
| Empty-string key | A real key, not the root. The test { '': { x: 1 }, x: 2 } flattens to .x and x, two distinct keys |
| Hostile keys | Writes use Object.defineProperty, so unflatten({'__proto__.polluted': 'yes'}) builds an own property named __proto__ and Object.prototype stays clean |
| Shared (non-circular) references | { a: shared, b: shared } flattens normally, because ancestors.delete(value) removes a container on the way up; leaving that line out makes the test throw "circular reference" |
| Contradictory input | {a: 1, 'a.b': 2} in either order throws conflict, instead of silently dropping one |
Limits to state
- The root must be a plain object, and
flattenthrowsTypeErrorfor an array root: an empty root array and an empty root object would both flatten to{}, so the format could not tell them apart. - Sparse arrays:
flattenproduces no key for a hole. A hole before a later element is rebuilt, because the index in the key (a[1]) leaves a gap whenunflattenassigns it, but a trailing hole is lost, since no key records the array's length ([1, ,]comes back as[1]). undefinedleaves are kept as the valueundefined;Dateand other non-plain objects are leaves and are shared by reference with the input, not copied.
Complexity
Both directions are linear in the number of leaves and total path length. flatten visits each node once per path that reaches it and builds one path string per visit; for tree-shaped data (what JSON gives) that is once per node, so its time is about the number of nodes times the typical path length (close to L, the characters of keys written, for bushy data; a single deep chain copies prefixes of growing length, which is quadratic in depth on engines that copy on concatenation), plus an O(d) ancestor set (the containers on the path from the root to the current value, which is how a loop is detected) for cycle detection at nesting depth d. unflatten parses each path in one pass over its characters and does one own-property lookup per step, so O(L) overall. The flat result holds one path string per leaf, so memory is O(n + L) extra. Shared references change the count: an object reachable by two paths is walked and written twice, because the flat form has one key per path. Measured on an input where each level references the next level twice (k + 1 distinct objects), flatten returns 1,024 keys for k = 10, 32,768 for k = 15 and 262,144 for k = 18: exponential in the number of distinct objects, which is inherent to the format.
Pitfalls
- Using
split('.')as the parser: it breaks on escaped dots and bracket indices. - Guessing arrays from digit-only keys, which turns
{0: 'x'}into['x']. - Dropping empty objects, which makes
{filters: {}}come back as{}. - Writing with
obj[key] = valuewhile parsing keys from untrusted input.
Running the code
Save the listing as flatten.mjs (the .mjs extension lets Node read import as an ES module) and run it with Node 22, which needs no packages:
node flatten.mjs
Write your own version of Promise.allSettled for an environment that lacks it. It accepts an iterable of promises or plain values and resolves with one outcome per input in input order. Say how you would treat an empty input.
Sample Answer
Direct answer
allSettled returns a promise that waits for every input to finish, whether it succeeds or fails, and then fulfils with an array of outcome objects in the same order as the inputs. It never rejects because of an input. Each outcome is { status: 'fulfilled', value } or { status: 'rejected', reason }. Wrap each input in Promise.resolve so plain values and thenables (objects with a .then method) are handled, store each outcome at its input's index, and count down until every slot is filled. An empty input fulfils immediately with [], because there is nothing to wait for and the countdown would otherwise never reach zero.
Implementation
import assert from 'node:assert/strict';
function allSettled(iterable) {
return new Promise((resolve, reject) => {
let items;
try { items = [...iterable]; } catch (err) { reject(err); return; } // non-iterable input rejects, as the native method does
const results = new Array(items.length);
let pending = items.length;
if (pending === 0) { resolve(results); return; } // empty input: fulfil with [] right away
items.forEach((item, i) => {
Promise.resolve(item).then(
(value) => { results[i] = { status: 'fulfilled', value }; if (--pending === 0) resolve(results); },
(reason) => { results[i] = { status: 'rejected', reason }; if (--pending === 0) resolve(results); }
);
});
});
}
// a buggy version that stores results in completion order, to prove the checks can fail
function allSettledWrongOrder(iterable) {
return new Promise((resolve) => {
const items = [...iterable]; const out = [];
if (!items.length) return resolve(out);
items.forEach((item) => Promise.resolve(item).then(
(value) => { out.push({ status: 'fulfilled', value }); if (out.length === items.length) resolve(out); },
(reason) => { out.push({ status: 'rejected', reason }); if (out.length === items.length) resolve(out); }));
});
}
const delay = (ms, v, fail) => new Promise((res, rej) => setTimeout(() => (fail ? rej(v) : res(v)), ms));
const thenable = { then(ok) { ok('from thenable'); } };
const rejectingThenable = { then(_ok, no) { no('nope'); } };
const cases = {
'mixed, slow first': () => [delay(30, 'slow'), 7, delay(10, 'boom', true), thenable],
'empty array': () => [],
'string is iterable': () => 'ab',
'set': () => new Set([1, Promise.resolve(2)]),
'generator': () => (function* () { yield delay(5, 'g1'); yield Promise.reject(new Error('g2')); })(),
'falsy values and reasons': () => [undefined, null, 0, '', NaN, Promise.reject(undefined), Promise.reject(null), rejectingThenable],
};
// a result that never arrives or an unexpected rejection becomes a FAIL line, not a hang or a crash
const settleWithin = (p, ms = 500) => {
let timer;
const limit = new Promise((_, rej) => { timer = setTimeout(() => rej(new Error('never settled')), ms); });
return Promise.race([p, limit]).finally(() => clearTimeout(timer));
};
async function check(name, impl) {
const failures = [];
for (const [label, make] of Object.entries(cases)) {
try {
const [mine, native] = await Promise.all([settleWithin(impl(make())), Promise.allSettled(make())]);
assert.deepStrictEqual(mine, native);
} catch (e) { failures.push(label + (e?.message === 'never settled' ? ' (never settled)' : '')); }
}
for (const bad of [5, undefined, {}]) {
const m = await settleWithin(impl(bad)).then(() => 'resolved', (e) => e.constructor.name);
const n = await Promise.allSettled(bad).then(() => 'resolved', (e) => e.constructor.name);
if (m !== n) failures.push(`non-iterable ${String(bad)}: ${m} vs ${n}`);
}
console.log(name.padEnd(22), failures.length ? 'FAIL -> ' + failures.join('; ') : 'PASS');
}
await check('allSettled', allSettled);
await check('allSettledWrongOrder', allSettledWrongOrder);
console.log(JSON.stringify(await allSettled([delay(30, 'slow'), 7, delay(10, 'boom', true)])));
console.log(JSON.stringify(await allSettled([])));
Run in a node:22 container (Node v22), it prints:
allSettled PASS
allSettledWrongOrder FAIL -> mixed, slow first; generator
[{"status":"fulfilled","value":"slow"},{"status":"fulfilled","value":7},{"status":"rejected","reason":"boom"}]
[]
The first two lines come from the check harness. In it, delay(ms, v, fail) builds a promise that settles after a timer, thenable and rejectingThenable are plain objects with a then method, and cases is a table of input factories (a function per case, so each implementation gets fresh promises). For each case it awaits both implementations at once and compares them with assert.deepStrictEqual, which treats two Error objects with the same name and message as equal and also checks that values such as undefined, null, 0, '' and NaN come back unchanged. It compares the polyfill's output with the built-in Promise.allSettled on six inputs (a mix where the slow promise is first, an empty array, a string, a Set, a generator, and a list of falsy values and falsy rejection reasons) and on three non-iterable inputs (5, undefined, {}), which must reject with the same error type as the built-in. settleWithin races each polyfill call against a 500 ms limit and every case sits in a try, so an implementation that never settles or that rejects prints a FAIL line naming the case (for example FAIL -> empty array (never settled) when the empty-input check is removed) and does not hang or crash the script. The second implementation deliberately stores results in completion order; the harness fails it on the slow-first case and on the generator, which shows the order check can fail. The last two lines show the real outputs: the slow promise stays first in the array although it settles last, and [] for the empty input.
How it works
A trace on three inputs makes the countdown concrete: [delay(30, 'slow'), 7, delay(10, 'boom', true)]. The array has length 3, so pending starts at 3 and results has three empty slots. The plain 7 is wrapped by Promise.resolve and its callback runs first, in a microtask: results[1] becomes { status: 'fulfilled', value: 7 } and pending drops to 2. After 10 ms the third input rejects: results[2] becomes { status: 'rejected', reason: 'boom' } and pending is 1. After 30 ms the first input fulfils: results[0] is filled, pending reaches 0 and the outer promise resolves with the array, in input order.
- Collect the input.
[...iterable]accepts anything iterable (an object that can be walked withfor...ofor spread: arrays, strings, Sets, generators) and throws aTypeErrorfor non-iterables. Because that throw happens inside thenew Promiseexecutor, it becomes a rejection of the returned promise, so a bad argument produces a rejected promise and not a synchronous exception. (The explicittry/catchmakes that visible; the executor would convert the throw into a rejection on its own.) - Normalise each item with
Promise.resolve(item). A real promise passes through unchanged, a plain value becomes an already-fulfilled promise, and a thenable is adopted. - Record by index, not by arrival. The callbacks write to
results[i], whereiis the item's position in the input. Completion order is irrelevant. This is what the broken variant gets wrong withpush. - Handle both outcomes in one
.then(onFulfilled, onRejected)call. Both callbacks resolve the outer promise only when the countdown (pending) reaches zero. Passing the rejection handler as the second argument ofthenmeans a rejected input is turned into data, so there is no unhandled rejection and the outer promise never rejects. - Empty input.
pendingstarts at 0, no callback will ever run, so the code resolves right away with[].
Running the code
Save the listing as all-settled.mjs (the .mjs extension lets Node read import and top-level await as an ES module) and run it with Node 22, which needs no packages:
node all-settled.mjs
Complexity and edge cases
- Time is O(n) work to attach handlers, plus whatever the inputs take; the result completes when the slowest input does. Space is O(n) for the results array.
- Rejection reasons can be anything, including
undefined. Because the code stores an object per outcome,{ status: 'rejected', reason: undefined }is distinguishable from a fulfilledundefined, which a bare array of values could not do. - Timing of the callbacks.
.thencallbacks always run asynchronously (as microtasks: small jobs the engine runs right after the current code finishes and before any timer), even for already-settled inputs, so the outer promise settles asynchronously for an empty input as well: the promise is already fulfilled but its.thenhandlers still run later. - Subclasses. The built-in calls
this.resolveso thatMySubclass.allSettledreturns an instance of the subclass. A subclass is a class built withclass MyPromise extends Promise; a simple polyfill that uses the globalPromisedoes not; mention it if asked, and it is rarely needed. - Feature detection. Install it only when it is missing:
if (!Promise.allSettled) Promise.allSettled = allSettled;. Replacing a native implementation gains nothing and loses details such as subclass support. - Contrast with the neighbours.
Promise.allrejects on the first rejection,Promise.anyfulfils on the first fulfilment, andPromise.racesettles with the first outcome of either kind.allSettledis the one to use when partial failure is a normal result, for example loading several independent dashboard widgets and showing an error card for each one that failed.
Design a debounce utility flexible enough for three cases: a search box that fires after typing pauses, a save button that must react on the first click and ignore repeats, and a component that must abort any pending call when it unmounts. Implement it, preserve this and arguments, and say when you would pick throttle instead.
Sample Answer
One debounce can serve all three cases if it exposes two edges and a cancel switch. A "burst" is a run of calls with gaps shorter than wait. The trailing edge runs the function after the burst goes quiet (search box). The leading edge runs it at the first call of the burst and ignores the rest (save button). cancel() drops anything still pending (unmount: React removing the component from the page). Throttle is the better pick when the input never goes quiet and you still want regular updates, such as scroll, resize or drag.
How each case maps to options
| Case | Options | What happens |
|---|---|---|
| Search box fires after typing pauses | { trailing: true } (default) | Runs once, wait ms after the last keystroke, with the last arguments |
| Save button reacts to the first click and ignores repeats | { leading: true, trailing: false } | Runs immediately; later clicks are ignored while the burst lasts |
| Component aborts pending work on unmount | cancel() called from the effect cleanup | The timer is cleared and the stored arguments are dropped |
The utility, typed in TypeScript
The generic signature keeps callers' types: A is the tuple of parameter types, R the return type, and T the type of this that fn declares. Four pieces of TypeScript syntax are used below:
A extends unknown[]saysAmust be a list type, so...args: Acan capture any parameter list as a tuple (a fixed-length list with a type per position).this: Tas the first parameter is not a real argument. It only tells the compiler whatthismust be when the function is called, and it disappears from the compiled JavaScript.ReturnType<typeof setTimeout>means "whateversetTimeoutreturns": a number in browsers and aTimeoutobject in Node, so the code hard-codes neither.// @ts-expect-error(in the test) states that the next line must contain a type error; if the compiler finds none, the build fails.
The wrapper returns R | undefined because before the first run (or while only a trailing call is pending) there is no result yet. Hiding that behind R would let callers use a value that does not exist.
export interface DebounceOptions {
leading?: boolean; // run on the first call of a burst
trailing?: boolean; // run once the burst has been quiet for `wait` ms
}
export interface Debounced<T, A extends unknown[], R> {
(this: T, ...args: A): R | undefined; // undefined until fn has run once
cancel(): void;
flush(): R | undefined;
pending(): boolean;
}
export function debounce<T, A extends unknown[], R>(
fn: (this: T, ...args: A) => R,
wait: number,
{ leading = false, trailing = true }: DebounceOptions = {}
): Debounced<T, A, R> {
if (!leading && !trailing) throw new RangeError('enable leading, trailing or both');
let timer: ReturnType<typeof setTimeout> | undefined;
let lastArgs: A | undefined; // arguments waiting for the trailing call
let lastThis: T | undefined;
let result: R | undefined;
const invoke = (): void => {
const args = lastArgs as A;
const ctx = lastThis as T;
lastArgs = undefined;
lastThis = undefined;
result = fn.apply(ctx, args);
};
const endOfBurst = (): void => {
timer = undefined;
if (trailing && lastArgs) invoke(); // a lone leading call leaves lastArgs empty
lastArgs = undefined;
lastThis = undefined;
};
function debounced(this: T, ...args: A): R | undefined {
const startsBurst = timer === undefined;
lastArgs = args;
lastThis = this;
clearTimeout(timer);
timer = setTimeout(endOfBurst, wait);
if (leading && startsBurst) invoke();
return result;
}
debounced.cancel = (): void => {
clearTimeout(timer);
timer = undefined;
lastArgs = undefined;
lastThis = undefined;
};
debounced.flush = (): R | undefined => {
if (timer !== undefined) {
clearTimeout(timer);
endOfBurst();
}
return result;
};
debounced.pending = (): boolean => timer !== undefined;
return debounced;
}
Proof that each case behaves as described
The test file drives a virtual clock one millisecond at a time, so the printed times are exact. It also renders a React 18 component to prove the unmount case. The setup is in the last section.
The test has five numbered sections that map to the question like this: section 1 is the search box, section 2 the save button, section 5 the unmount; section 3 covers forwarding of this and arguments and the both-edges case; section 4 covers flush and cancel. The React pieces in section 5: a component is mounted when React first puts it on the page, rendered each time React calls the component function, and an effect (useEffect) is code React runs after rendering. The function an effect returns is its cleanup: React calls it before re-running the effect with new inputs and when the component unmounts. act is a testing helper that makes React finish pending updates and effects before the test continues (react.dev, act).
import assert from 'node:assert/strict';
import { mock } from 'node:test';
import { JSDOM } from 'jsdom';
import { useEffect, useState } from 'react';
import { debounce } from './debounce.js';
// Browser globals for React, set before React Testing Library is imported
// (React Testing Library reads window and document when it loads, and Node has neither).
const dom = new JSDOM('<!doctype html><body></body>');
Object.assign(globalThis, { window: dom.window, document: dom.window.document });
Object.defineProperty(globalThis, 'navigator', { value: dom.window.navigator, configurable: true });
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; // tells React it runs inside a test that uses act()
const { render, act } = await import('@testing-library/react');
mock.timers.enable({ apis: ['setTimeout'], now: 0 });
let now = 0; // virtual clock in ms, advanced one tick at a time
const advanceTo = (t: number) => {
while (now < t) {
now++;
mock.timers.tick(1);
}
};
const log: string[] = [];
// 1. Search box: trailing edge only (the default).
const searched: string[] = [];
const search = debounce((q: string) => void searched.push(`${q}@${now}`), 300);
search('r'); advanceTo(100); search('re'); advanceTo(200); search('rea');
advanceTo(499);
assert.deepEqual(searched, []);
advanceTo(500);
log.push(`search -> ${searched}`);
assert.deepEqual(searched, ['rea@500']);
// 2. Save button: leading edge only. Repeats inside the window are ignored,
// and each ignored click also extends the window.
const saves: number[] = [];
const save = debounce(() => void saves.push(now), 1000, { leading: true, trailing: false });
advanceTo(1000); save(); // runs at once
advanceTo(1300); save(); // ignored
advanceTo(1600); save(); // ignored, window now ends at 2600
advanceTo(2599); save(); // ignored, window now ends at 3599
advanceTo(3600); save(); // quiet for 1000 ms, runs again
log.push(`save -> ${saves}`);
assert.deepEqual(saves, [1000, 3600]);
// 3. this and arguments are forwarded; leading + trailing with a single call runs once.
const cart = {
items: 3,
report: debounce(function (this: { items: number }, tag: string) {
return `${tag}:${this.items}`;
}, 100),
};
cart.report('a'); cart.report('b');
advanceTo(now + 100);
assert.equal(cart.report.flush(), 'b:3');
const both: string[] = [];
const bothEdges = debounce((s: string) => void both.push(`${s}@${now}`), 100, { leading: true, trailing: true });
bothEdges('x'); // leading call at 3700, nothing pending afterwards
advanceTo(3800); bothEdges('p'); // new burst, leading call at 3800
advanceTo(3850); bothEdges('q'); // second call of the burst, waits for the trailing edge
advanceTo(4000);
log.push(`both edges -> ${both}`);
assert.deepEqual(both, ['x@3700', 'p@3800', 'q@3950']);
// 4. cancel / flush
const flushed: string[] = [];
const f = debounce((s: string) => void flushed.push(s), 500);
f('draft'); assert.equal(f.pending(), true);
f.flush(); assert.deepEqual(flushed, ['draft']); assert.equal(f.pending(), false);
f('discarded'); f.cancel(); advanceTo(now + 1000);
assert.deepEqual(flushed, ['draft']);
log.push(`flush/cancel-> ${flushed}`);
// 5. Unmount cancels a pending call.
const sent: string[] = [];
function Search({ q }: { q: string }) {
const [, setN] = useState(0);
useEffect(() => {
const run = debounce((text: string) => { sent.push(text); setN((n) => n + 1); }, 300);
run(q);
return () => run.cancel(); // runs when q changes and when the component unmounts
}, [q]);
return null;
}
const view = render(<Search q="rea" />);
act(() => advanceTo(now + 299));
view.rerender(<Search q="react" />);
act(() => advanceTo(now + 299));
assert.deepEqual(sent, [], 'both earlier timers were cancelled by the effect cleanup');
view.unmount();
act(() => advanceTo(now + 1000));
log.push(`unmounted -> ${sent.length} calls after unmount`);
assert.deepEqual(sent, []);
// Compile-time checks: these lines must be type errors or the build fails.
// @ts-expect-error wrong argument type
search(42);
// @ts-expect-error `this` has to match what fn declared
cart.report.call({ items: 'many' }, 'a');
const typed: string | undefined = cart.report('z');
cart.report.cancel();
console.log(log.join('\n'));
Compiled with TypeScript 5 and run in a node:22 container, it prints:
search -> rea@500
save -> 1000,3600
both edges -> x@3700,p@3800,q@3950
flush/cancel-> draft
unmounted -> 0 calls after unmount
The two @ts-expect-error lines are checks too: if the types were too loose to reject search(42) or a wrong this, tsc would report an unused directive and the build would fail. Replacing the cleanup with an empty function makes the "both earlier timers were cancelled" assertion fail with ['rea'], so the harness does detect a missing cancel.
Reading the numbers
- Search: calls at 0, 100 and 200 ms with
wait = 300run once at 200 + 300 = 500 ms withrea, the last argument. - Save: the click at 1000 runs at once. Clicks at 1300, 1600 and 2599 are ignored, and each one restarts the 1000 ms window (so it ends at 3599). The click at 3600 finds the window closed and runs.
- Both edges:
xruns at 3700 and leaves nothing for the trailing edge, so there is no duplicate call. After a gap,pruns at 3800;qat 3850 is held and runs at 3850 + 100 = 3950.
Why uncleared timers leak or misfire
The timer variable is private to one debounced function, held by its closure (the function plus the variables it captured). A pending timer holds a reference to the callback, and the callback holds everything it captured, such as props, state setters and DOM nodes. If a component unmounts with a timer pending, the browser keeps all of that alive until the timer fires. The call then runs for a screen that no longer exists: a wasted network request, or a state update on a dead component. The cleanup that runs on unmount (run.cancel() above) removes both problems.
The opposite mistake is creating the debounced function inside a component body without keeping it. Every render builds a new closure with its own timer, so the previous timer is never cleared and the function behaves as if it was never debounced. The effect-scoped version above avoids this because the effect re-creates the wrapper only when q changes and cancels the old one first.
Debounce or throttle
Pick throttle (run at most once per interval, with calls in between skipped or merged) when events never pause and a steady stream of updates has value: scroll position, window resize, drag, a progress report during a long upload. A debounce on those would fire only after the user stops, so the page would look frozen while they scroll. Pick debounce when only the final state matters: search text, validation after typing, saving a settled draft.
Trade-offs and pitfalls
- Leading-only debounce is a weak double-submit guard. As the trace shows, a user who keeps clicking extends the window, and once it closes a click goes through again. For saves, also disable the button while the request is in flight and send an idempotency key (a unique id the server uses to ignore a repeated request).
leading: false, trailing: falsewould never call anything, so the code throws instead of returning a dead function.- Use
flush()for Enter or blur, where the user expects the pending call to happen now. - Each wrapper costs O(1) time per call and O(1) space: one timer, the latest arguments and the last result.
- If
fnthrows on the trailing edge, the error surfaces from the timer callback, not from the call site that triggered it. Handle errors insidefn.
Running the code
Put the utility in debounce.ts, the test in debounce.test.tsx, and next to them package.json containing { "type": "module" } and this tsconfig.json:
{ "compilerOptions": { "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext",
"jsx": "react-jsx", "strict": true, "outDir": "dist", "skipLibCheck": true },
"include": ["*.ts", "*.tsx"] }
Then, with Node 22:
npm i react@18 react-dom@18 @testing-library/react@14 jsdom typescript@5 @types/react@18 @types/react-dom@18 @types/node@22 @types/jsdom
npx tsc && node dist/debounce.test.js
Implement deepClone in JavaScript for application data containing arrays, plain objects, Dates, RegExps and nested combinations. You may assume no circular references. Explain what your version gets wrong and which inputs it does not support.
Sample Answer
Direct answer
A deep clone copies a value and everything reachable from it, so changing the copy never changes the original. Recursive means the function calls itself on each nested value. The recursive version dispatches on type: primitives (and functions) are returned as they are, arrays are rebuilt element by element, a Date is rebuilt from its timestamp, a RegExp from its source and flags, and a plain object is rebuilt key by key. Anything else (a Map, a Set, a typed array, a DOM node) is refused with a TypeError instead of being silently flattened into an empty object. The version below assumes no circular references, so a cycle makes it recurse until the call stack (the engine's fixed-size record of the functions currently running) overflows, which JavaScript reports as a RangeError.
Implementation
The terms the code relies on: an enumerable property is one that Object.keys and for...in list (properties created by ordinary assignment are enumerable); a prototype is the object a value inherits its methods from (the prototype of an array is Array.prototype); Object.defineProperty creates a property from a descriptor object (value, writable, enumerable, configurable) and, unlike assignment, never triggers the __proto__ setter.
import assert from 'node:assert/strict';
function setOwn(target, key, value) {
// defineProperty so a key named "__proto__" becomes data, not a prototype change
Object.defineProperty(target, key, {
value, writable: true, enumerable: true, configurable: true,
});
}
function deepClone(value) {
if (value === null || typeof value !== 'object') return value; // primitives and functions
if (Array.isArray(value)) {
const out = new Array(value.length); // holes in sparse arrays stay holes
for (const i of Object.keys(value)) out[i] = deepClone(value[i]);
return out;
}
if (value instanceof Date) return new Date(value.getTime());
if (value instanceof RegExp) {
const copy = new RegExp(value.source, value.flags);
copy.lastIndex = value.lastIndex;
return copy;
}
const tag = Object.prototype.toString.call(value);
if (tag !== '[object Object]') {
throw new TypeError(`deepClone: unsupported ${tag}`);
}
const out = {};
for (const key of Object.keys(value)) setOwn(out, key, deepClone(value[key]));
return out;
}
// Strict JSON-compatible variant: throws instead of guessing.
function jsonClone(value, ancestors = new Set()) {
switch (typeof value) {
case 'string': case 'boolean': return value;
case 'number':
if (!Number.isFinite(value)) throw new TypeError(`jsonClone: ${value} is not JSON-safe`);
return value;
case 'object': break;
default: throw new TypeError(`jsonClone: unsupported ${typeof value}`);
}
if (value === null) return null;
if (ancestors.has(value)) throw new TypeError('jsonClone: circular reference');
ancestors.add(value);
let out;
if (Array.isArray(value)) {
out = Array.from({ length: value.length }, (_, i) => jsonClone(value[i], ancestors));
} else if (Object.prototype.toString.call(value) === '[object Object]') {
out = {};
for (const key of Object.keys(value)) setOwn(out, key, jsonClone(value[key], ancestors));
} else {
throw new TypeError(`jsonClone: unsupported ${Object.prototype.toString.call(value)}`);
}
ancestors.delete(value); // only ancestors count: shared, non-circular references are legal
return out;
}
// --- harness ---
const src = {
id: 7,
tags: ['a', ['b']],
when: new Date('2024-05-01T00:00:00Z'),
pattern: /ab+c/gi,
nested: { deep: { list: [{ n: 1 }] } },
};
const copy = deepClone(src);
assert.deepEqual(copy, src);
assert.notEqual(copy.nested.deep, src.nested.deep);
assert.notEqual(copy.when, src.when);
copy.nested.deep.list[0].n = 99;
copy.tags[1].push('c');
assert.equal(src.nested.deep.list[0].n, 1);
assert.deepEqual(src.tags, ['a', ['b']]);
const cursor = /a/g; cursor.lastIndex = 3;
assert.equal(deepClone(cursor).lastIndex, 3); // the regex cursor is copied
const x = { v: 1 };
const dup = deepClone({ a: x, b: x });
assert.notEqual(dup.a, dup.b); // a shared reference becomes two copies
assert.deepEqual(dup.a, dup.b);
console.log(copy.when instanceof Date, copy.pattern instanceof RegExp, String(copy.pattern));
// the __proto__ trap
const hostile = JSON.parse('{"__proto__": {"polluted": true}}');
const cloned = deepClone(hostile);
assert.equal(({}).polluted, undefined);
assert.equal(Object.getPrototypeOf(cloned), Object.prototype);
console.log('proto key copied as data:', Object.keys(cloned));
// what deepClone does not support
for (const [label, input] of [
['Map', new Map([[1, 2]])], ['Set', new Set([1])], ['Uint8Array', new Uint8Array(2)],
]) {
try { deepClone(input); console.log(label, 'cloned'); }
catch (e) { console.log(label, '->', e.message); }
}
const f = () => 1;
console.log('function shared by reference:', deepClone({ f }).f === f);
class Point { constructor() { this.x = 1; } len() { return 1; } }
const pc = deepClone(new Point());
console.log('class instance prototype kept:', pc instanceof Point, typeof pc.len);
const sym = Symbol('k');
console.log('symbol keys copied:', Object.getOwnPropertySymbols(deepClone({ [sym]: 1 })).length);
let chain = {}; let tip = chain;
for (let i = 0; i < 1_000_000; i++) { tip.next = {}; tip = tip.next; }
try { deepClone(chain); } catch (e) { console.log('depth 1,000,000 ->', e.constructor.name); }
// jsonClone
const ok = jsonClone({ a: [1, { b: null }], c: 'x' });
assert.deepEqual(ok, { a: [1, { b: null }], c: 'x' });
console.log(JSON.stringify(ok));
const shared = { v: 1 };
console.log('shared ref ok:', JSON.stringify(jsonClone({ p: shared, q: shared })));
class User { constructor() { this.name = 'Ada'; } }
const u = jsonClone(new User());
console.log('prototype dropped:', u instanceof User, Object.getPrototypeOf(u) === Object.prototype);
const loop = { name: 'loop' }; loop.self = loop;
for (const [label, input] of [
['function', { f }], ['symbol', { s: sym }], ['undefined', { u: undefined }],
['NaN', { n: NaN }], ['bigint', { b: 1n }], ['Date', { d: new Date(0) }], ['cycle', loop],
]) {
assert.throws(() => jsonClone(input), TypeError);
try { jsonClone(input); } catch (e) { console.log(label.padEnd(9), '->', e.message); }
}
Run in a node:22 container, it prints:
true true /ab+c/gi
proto key copied as data: [ '__proto__' ]
Map -> deepClone: unsupported [object Map]
Set -> deepClone: unsupported [object Set]
Uint8Array -> deepClone: unsupported [object Uint8Array]
function shared by reference: true
class instance prototype kept: false undefined
symbol keys copied: 0
depth 1,000,000 -> RangeError
{"a":[1,{"b":null}],"c":"x"}
shared ref ok: {"p":{"v":1},"q":{"v":1}}
prototype dropped: false true
function -> jsonClone: unsupported function
symbol -> jsonClone: unsupported symbol
undefined -> jsonClone: unsupported undefined
NaN -> jsonClone: NaN is not JSON-safe
bigint -> jsonClone: unsupported bigint
Date -> jsonClone: unsupported [object Date]
cycle -> jsonClone: circular reference
Each assert throws on failure, so the file stops at the first broken expectation.
Why each branch looks the way it does
- Primitives and functions.
typeof value !== 'object'covers numbers, strings, booleans,undefined, symbols, bigints and functions. A function cannot be meaningfully copied, so the clone shares it by reference (the output showsfunction shared by reference: true). - Arrays.
new Array(length)plusObject.keyscopies only the indices that exist, so holes stay holes. A sparse array has missing indices, as in[1, , 3]: index 1 is a hole, andObject.keys([1, , 3])is['0', '2']. Date.new Date(value.getTime()). Copying aDatewithObject.keyswould yield{}, because a date keeps its time in an internal slot (hidden storage the engine attaches to built-in objects, not visible as a property) rather than in properties.RegExp.new RegExp(source, flags)and thenlastIndexis copied, because a global or sticky regex carries a cursor betweenexeccalls.- Everything else throws.
Object.prototype.toString.call(value)returns a tag such as[object Map], so the error message names the unsupported type. A class instance reports[object Object]and so is copied as a plain object. - Plain objects. Own enumerable string keys are copied with
Object.defineProperty, notout[key] = .... A JSON payload can contain a key literally named"__proto__"; assigning it would swap the clone's prototype. The run shows it copied as ordinary data and({}).pollutedstayingundefined.
To see what plain assignment would do, run this on its own:
const out = {};
out['__proto__'] = { polluted: true }; // plain assignment
console.log(Object.keys(out), out.polluted, Object.getPrototypeOf(out) === Object.prototype);
console.log(({}).polluted);
Run in a node:22 container, it prints:
[] true false
undefined
The assignment does not create a key (Object.keys is empty). It calls the __proto__ setter, which makes the hostile object the prototype of out, so out.polluted is true by inheritance and out's own prototype is no longer Object.prototype. Other objects stay clean (({}).polluted is undefined), but the clone now carries properties the data never had.
Tracing the recursion
For deepClone({ a: [1, { b: 2 }] }) the calls happen in this order:
- The outer object is not an array,
DateorRegExp, and its tag is[object Object], so a new{}is made and its keyais visited. deepClone([1, { b: 2 }]): an array, sonew Array(2)is made and keys'0'and'1'are visited.deepClone(1)returns1at once (a primitive).deepClone({ b: 2 })makes another{}and visitsb.deepClone(2)returns2; the inner{}becomes{ b: 2 }, a new object.- The array is completed as
[1, { b: 2 }](new), then stored underaof the new outer object.
Every container on the way is a fresh object, and only primitives are shared, which is why changing the copy cannot touch the original.
What this version gets wrong, and which inputs it does not support
| Input | What happens |
|---|---|
| Circular reference | Unbounded recursion, ending in RangeError: Maximum call stack size exceeded |
Shared reference ({a: x, b: x}) | Copied twice, so copy.a !== copy.b where the original had a === b; heavily shared data is copied once per path, which can be exponential |
Map, Set, typed arrays, ArrayBuffer, Error, Promise | Throws TypeError |
| Class instances | Copied as plain objects: the prototype is dropped, so instanceof and methods are lost (output: class instance prototype kept: false) |
| Symbol keys, non-enumerable properties, getters and setters | Symbol keys are not copied (symbol keys copied: 0), non-enumerable properties are skipped, and a getter is read once and stored as a plain value |
| Functions | Shared with the original, not copied |
| Very deep data | A chain 1,000,000 levels deep raises RangeError. An explicit stack (a loop that keeps its own list of values still to copy, instead of using the call stack) removes the limit |
Where the data fits, the built-in structuredClone (a global function that deep-copies values using the browser's and Node's own serialisation rules) handles circular references and throws DataCloneError for input it cannot serialize (MDN, structuredClone). A hand-written clone is justified when you need the exact rules above, or when the runtime has no structuredClone.
A strict JSON-compatible version
jsonClone accepts only what JSON can represent faithfully: strings, booleans, finite numbers, null, arrays and objects. It throws on functions, symbols, undefined, bigint, NaN and Infinity, Date and the other built-ins, and circular references. A class instance is copied as a plain object, which is what "drop the prototype" means here: the output's prototype is Object.prototype.
The cycle check tracks the current ancestors only. The set adds a node on the way down and removes it on the way up, so {p: shared, q: shared} is legal (a shared reference is not a cycle) while loop.self = loop throws. The output above shows each rejection with its message and the shared-reference case succeeding.
| Input | Result |
|---|---|
{a: [1, {b: null}], c: 'x'} | A structurally identical copy |
{f: fn} | TypeError: jsonClone: unsupported function |
{s: Symbol('k')} | TypeError: jsonClone: unsupported symbol |
{n: NaN} | TypeError: jsonClone: NaN is not JSON-safe |
{d: new Date(0)} | TypeError: jsonClone: unsupported [object Date] |
loop with loop.self = loop | TypeError: jsonClone: circular reference |
Throwing is the point: JSON.parse(JSON.stringify(x)) is the usual shortcut, and it silently drops undefined, functions and symbols and turns NaN into null (MDN, JSON.stringify), so the data comes back changed without any error.
Complexity
For tree-shaped data (no object reachable by two paths) both versions visit each node once: O(n) time for n nodes and values. Neither version remembers what it has already copied, so a shared object is copied again on every path that reaches it. Data in which many objects are shared (a directed acyclic graph) therefore costs one visit per path, not per node, which can be exponential: a chain of 20 objects in which each one references the next one twice (21 distinct objects) makes 3,145,727 deepClone calls, because every level doubles the count. Space is O(size of the copy) plus O(d) call stack for nesting depth d. jsonClone adds an O(d) ancestor set. A clone that tracks visited objects in a Map from original to copy is linear in the number of distinct nodes and also handles cycles.
Pitfalls
- Using
JSON.parse(JSON.stringify(x))as the general answer: it fails on dates (they become strings),undefined,NaN,Map,Setand cycles. - Writing
out[key] = ...with keys from untrusted data. - Mistaking a shallow copy (
{...x},Array.from) for a deep one: nested objects remain shared.
Running the code
Save the first listing as clone.mjs (the .mjs extension lets Node read import as an ES module) and run it with Node 22, which needs no packages:
node clone.mjs
Implement getNested(obj, path, defaultValue) that reads a deeply nested property without throwing when an intermediate value is missing. The path may be given in more than one form. Show usage.
Sample Answer
Direct answer
getNested(obj, path, defaultValue) first turns the path into a list of keys, then walks the object one key at a time. If the current value is null or undefined, or does not have the next key, it stops and returns defaultValue. A path names where a value sits inside nested data. It can be a string in dotted or bracket form ('orders[0].items[0].sku', 'orders.0.id') or an array of keys (['a.b']), and the array form is the one that works for keys that themselves contain a dot. Nothing is evaluated as code: parsing is a small regular expression, so there is no eval or new Function.
Implementation and usage
import assert from 'node:assert/strict';
// "a.b[0].c" or a["x.y"].z -> ['a', 'b', '0', 'c']; an array path is used as given
function toPath(path) {
if (Array.isArray(path)) return path.map(String);
const parts = [];
const token = /[^.[\]]+|\[(?:(\d+)|(["'])(.*?)\2)\]/g;
let m;
while ((m = token.exec(path)) !== null) {
parts.push(m[3] !== undefined ? m[3] : m[1] !== undefined ? m[1] : m[0]);
}
return parts;
}
function getNested(obj, path, defaultValue) {
let cur = obj;
for (const key of toPath(path)) {
if (cur === null || cur === undefined || !Object.hasOwn(Object(cur), key)) {
return defaultValue;
}
cur = cur[key];
}
return cur === undefined ? defaultValue : cur;
}
const user = {
name: 'Ada',
address: { city: 'London', geo: null, zip: '' },
orders: [{ id: 'o1', items: [{ sku: 'k1', qty: 0 }] }],
'a.b': 'dotted key',
count: 0,
};
const rows = [
['address.city', getNested(user, 'address.city')],
['orders[0].items[0].sku', getNested(user, 'orders[0].items[0].sku')],
['orders.0.id', getNested(user, 'orders.0.id')],
[`["orders",0,"id"] (array)`, getNested(user, ['orders', 0, 'id'])],
[`['a.b'] (quoted key)`, getNested(user, "['a.b']")],
[`["a.b"] (array form)`, getNested(user, ['a.b'])],
['address.country.code', getNested(user, 'address.country.code', 'n/a')],
['address.geo.lat (null mid-path)', getNested(user, 'address.geo.lat', 'n/a')],
['address.geo (null value)', getNested(user, 'address.geo', 'n/a')],
['count (0 is kept)', getNested(user, 'count', 99)],
['address.zip ("" is kept)', getNested(user, 'address.zip', 'n/a')],
['orders[0].items[0].qty', getNested(user, 'orders[0].items[0].qty', 99)],
['name.length (string)', getNested(user, 'name.length')],
['orders[3].id (past the end)', getNested(user, 'orders[3].id', 'none')],
['constructor (inherited)', getNested(user, 'constructor', 'blocked')],
['null object', getNested(null, 'a.b', 'dflt')],
['empty path returns obj', getNested(user, '') === user],
];
for (const [label, value] of rows) console.log(label.padEnd(34), JSON.stringify(value));
assert.equal(getNested(user, 'address.city'), 'London');
assert.equal(getNested(user, 'orders[0].items[0].sku'), 'k1');
assert.equal(getNested(user, 'orders.0.id'), 'o1');
assert.equal(getNested(user, ['a.b']), 'dotted key');
assert.equal(getNested(user, "['a.b']"), 'dotted key'); // quoted bracket form in a string path
assert.equal(getNested(user, '["a.b"].x', 'none'), 'none');
assert.equal(getNested(user, 'name.length'), 3);
assert.equal(getNested(user, 'orders[3].id', 'none'), 'none');
assert.equal(getNested(user, 'address.country.code', 'n/a'), 'n/a');
assert.equal(getNested(user, 'count', 99), 0);
assert.equal(getNested(user, 'address.geo', 'n/a'), null);
assert.equal(getNested(user, 'constructor', 'blocked'), 'blocked');
assert.equal(getNested(undefined, 'x'), undefined);
Run in a node:22 container, it prints:
address.city "London"
orders[0].items[0].sku "k1"
orders.0.id "o1"
["orders",0,"id"] (array) "o1"
['a.b'] (quoted key) "dotted key"
["a.b"] (array form) "dotted key"
address.country.code "n/a"
address.geo.lat (null mid-path) "n/a"
address.geo (null value) null
count (0 is kept) 0
address.zip ("" is kept) ""
orders[0].items[0].qty 0
name.length (string) 3
orders[3].id (past the end) "none"
constructor (inherited) "blocked"
null object "dflt"
empty path returns obj true
The assert lines at the bottom throw if any of the behaviours below change, including the quoted bracket form in a string path, the string length lookup and the index past the end.
How it works
-
Parsing. One regex matches either a run of characters other than
.,[and](a plain key), or a bracket group holding digits ([0]) or a quoted string (["a.b"],['a.b']). Quoted brackets let a string path name a key that contains a dot. An array path is used as given, with each key turned into a string. In the regex,(\d+)is capture group 1 (the index digits),(["'])is group 2 (the opening quote) and(.*?)is group 3 (the quoted text, with\2requiring the same closing quote). Eachtoken.exec(path)call returns the next matchm, wherem[0]is the whole match,m[1]the digits orundefined, andm[3]the quoted text orundefined. The linem[3] !== undefined ? m[3] : m[1] !== undefined ? m[1] : m[0]picks the quoted text if there is one, else the digits, else the plain key.Tokenising
orders[0].items[0].sku, one match at a time:Match m[0]m[1]m[3]Key pushed ordersundefined undefined orders[0]0undefined 0itemsundefined undefined items[0]0undefined 0skuundefined undefined skuThe dots between segments are skipped because the first alternative stops at
.and the regex finds the next match after it. For['a.b'].cthe first match is['a.b']withm[3]equal toa.b, thenc, giving the keysa.bandc. -
Walking. For each key, stop if the current value is
nullorundefined. Otherwise check that the key is an own property withObject.hasOwn(Object(cur), key)and step into it. An own property is stored directly on the object; an inherited one is found by following the object's prototype chain, the chain of parent objects the engine searches when a name is not on the object itself. Every plain object's chain ends atObject.prototype, which suppliesconstructor,toStringand__proto__, so theconstructorrow returns the default.Object(cur)wraps a primitive such as the string'Ada'in an object so thatObject.hasOwncan inspect it; the wrapper has its ownlengthproperty, as thename.lengthrow shows. -
Default. After the walk, if the result is
undefined, returndefaultValue.
Decisions worth stating
| Situation | Result | Reason |
|---|---|---|
Value is 0, '', false or null | The value itself (count gives 0, address.geo gives null) | The default replaces only a missing result (undefined). Testing truthiness (if (!value)) would replace real data |
null appears mid-path | The default | Reading a key of null would throw TypeError |
Index past the end (orders[3].id) | The default | The key does not exist |
Inherited names (constructor, toString, __proto__) | The default | Only own properties are followed, so a path built from user input cannot walk up the prototype chain. The price: an inherited getter defined on a class prototype is not reachable by this helper |
| Empty path | The object itself | Zero keys walked |
Optional chaining, user?.address?.geo?.lat, does the same walk for a path written in the source. getNested earns its place when the path is data: a column name from a config, a field path in a form schema, a key list from a URL.
Complexity
O(p) for a path with p keys: each step is one property lookup, and parsing is a single pass over the string. No recursion and no copying of the object.
Edge cases and pitfalls
'a.b'as a string means keya, then keyb. To read a key literally nameda.b, use the array form or the quoted bracket form.- Numeric segments are strings:
orders.0andorders[0]both look up the key'0', which is how arrays store indices. - Distinguish "present with value
undefined" from "missing": both return the default, by design. - Writing the parser with
path.split('.')alone breaks bracket syntax; writing it withevalornew Functionruns arbitrary input as code.
Running the code
Save the listing as get-nested.mjs (the .mjs extension lets Node read import as an ES module) and run it with Node 22, which needs no packages:
node get-nested.mjs
Unlock Full Question Bank
Get access to all 21 Polyfills and JavaScript Utility Implementation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.