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 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
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.
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
Implement throttle(fn, wait) so a handler runs at most once per interval. Use it to explain why scroll and resize handlers want throttle while a search box wants debounce.
Sample Answer
Throttle guarantees a maximum rate: however many times the wrapper is called, the real function runs at most once per wait milliseconds. Debounce waits for silence and then runs once. That is why scroll and resize handlers want throttle (they need updates while the user keeps moving, and the events never go quiet), while a search box wants debounce (only the finished text matters, and every intermediate request is wasted).
Implementation
Each call compares the current time with the time fn last ran. If a full window has passed, run now. Otherwise remember the newest arguments and make sure exactly one timer is waiting to run them when the window ends (the trailing call). Without that trailing call the last event of a burst can be lost: the user stops scrolling at a position that was never delivered.
import assert from 'node:assert/strict';
import { mock } from 'node:test';
// At most one call per `wait` ms. The first call runs at once (the leading edge,
// meaning the start of a burst of calls);
// calls that arrive inside the window are folded into ONE trailing call that
// carries the newest arguments and runs when the window ends.
function throttle(fn, wait, { trailing = true } = {}) {
let last = -Infinity; // when fn last ran
let timer; // pending trailing call
let pendingArgs;
let pendingThis;
function throttled(...args) {
const now = Date.now();
const remaining = wait - (now - last);
if (remaining <= 0) {
clearTimeout(timer); // a fresher call replaces any queued trailing one
timer = undefined;
pendingArgs = pendingThis = undefined;
last = now;
fn.apply(this, args);
} else if (trailing) {
pendingArgs = args;
pendingThis = this;
timer ??= setTimeout(() => {
timer = undefined;
last = Date.now();
const [a, c] = [pendingArgs, pendingThis];
pendingArgs = pendingThis = undefined;
fn.apply(c, a);
}, remaining);
}
}
throttled.cancel = () => {
clearTimeout(timer);
timer = pendingArgs = pendingThis = undefined;
last = -Infinity;
};
return throttled;
}
function debounce(fn, wait) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
};
}
// Virtual clock, advanced 1 ms at a time so Date.now() inside callbacks is exact.
function scenario(events, makeHandler) {
mock.timers.reset();
mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 0 });
const calls = [];
const handler = makeHandler((value) => calls.push(`${value}@${Date.now()}`));
let now = 0;
const last = events.at(-1).t;
for (const { t, value } of events) {
while (now < t) { now++; mock.timers.tick(1); }
handler(value);
}
while (now < last + 1000) { now++; mock.timers.tick(1); }
return calls;
}
// Scroll: 31 events, one every 16 ms from t = 0 to t = 480.
const scroll = Array.from({ length: 31 }, (_, i) => ({ t: i * 16, value: `y${i * 16}` }));
const scrollThrottled = scenario(scroll, (f) => throttle(f, 100));
const scrollDebounced = scenario(scroll, (f) => debounce(f, 100));
console.log('scroll events :', scroll.length);
console.log('throttle(100) calls :', scrollThrottled.join(' '));
console.log('debounce(100) calls :', scrollDebounced.join(' '));
// Typing: r, re, rea, reac, react, one key every 120 ms.
const typing = ['r', 're', 'rea', 'reac', 'react'].map((value, i) => ({ t: i * 120, value }));
console.log('typing throttle(300) :', scenario(typing, (f) => throttle(f, 300)).join(' '));
console.log('typing no trailing :', scenario(typing, (f) => throttle(f, 300, { trailing: false })).join(' '));
console.log('typing debounce(300) :', scenario(typing, (f) => debounce(f, 300)).join(' '));
// Checks that can fail.
const times = scrollThrottled.map((c) => Number(c.split('@')[1]));
assert.equal(times[0], 0, 'first call runs immediately');
for (let i = 1; i < times.length; i++) assert.ok(times[i] - times[i - 1] >= 100, 'never closer than wait');
assert.equal(scrollThrottled.at(-1), 'y480@500', 'the last position is delivered by the trailing call');
assert.equal(scrollDebounced.length, 1);
assert.equal(scenario(typing, (f) => throttle(f, 300)).at(-1), 'react@600');
assert.notEqual(scenario(typing, (f) => throttle(f, 300, { trailing: false })).at(-1)?.split('@')[0], 'react');
// `this` and the newest arguments reach both the leading and the trailing call.
mock.timers.reset();
mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 0 });
const seen = [];
const widget = { tag: 'w', hit: throttle(function (v) { seen.push(`${this.tag}:${v}@${Date.now()}`); }, 100) };
for (let ms = 0; ms <= 300; ms++) {
if (ms === 0) widget.hit(1);
if (ms === 30) widget.hit(2);
if (ms === 60) widget.hit(3);
mock.timers.tick(1);
}
assert.deepEqual(seen, ['w:1@0', 'w:3@100']);
Run in a node:22 container, the script prints the following. Times are milliseconds on a virtual clock advanced one millisecond at a time, and y96@100 means "called with y96, at 100 ms".
scroll events : 31
throttle(100) calls : y0@0 y96@100 y192@200 y288@300 y384@400 y480@500
debounce(100) calls : y480@580
typing throttle(300) : r@0 rea@300 react@600
typing no trailing : r@0 reac@360
typing debounce(300) : react@780
The assertions at the bottom pass: the first call runs at 0, no two calls are closer than wait, the trailing call delivers the final scroll position, the no-trailing variant never delivers react, and a last block checks that a method called as widget.hit(...) sees this as widget in both the leading call (w:1@0) and the trailing call, which carries the newest arguments (w:3@100, not w:2). Replacing fn.apply(c, a) or fn.apply(this, args) with a call that drops this makes the script throw.
Reading the scroll result
Thirty-one scroll events arrive between 0 and 480 ms (one every 16 ms, roughly a 60 Hz frame rate: a screen that redraws 60 times a second shows a new frame about every 16.7 ms). The throttled handler runs six times at 0, 100, 200, 300, 400 and 500 ms, each time with the newest position at that moment, so a header or progress bar tracks the scroll about ten times a second. The event at 96 ms arrives 4 ms before its window closes, so its trailing timer fires at 100 ms. The event at 480 ms arrives 20 ms before the window that started at 400 closes, so it is delivered at 500 ms.
The debounced handler runs once, at 480 + 100 = 580 ms, after the scrolling stopped. A progress bar driven by it would stay frozen during the whole scroll, which is the wrong behaviour for this event.
Reading the typing result
Five keystrokes, 120 ms apart, with wait = 300:
- Throttle sends
rat 0,reaat 300 andreactat 600: three requests, two of them for text the user had already moved past. - Throttle without the trailing call sends
rat 0 andreacat 360 and then dropsreact, so the request for the final text never happens. This is the failure the trailing call prevents. - Debounce sends one request,
react, at 480 + 300 = 780 ms.
For a search box the single request is cheaper for the server and avoids results flickering through partial queries. Throttle's one advantage here is that results for rea appear during typing, which is worth it only when instant partial feedback matters more than request count.
Choosing and improving
| Event | Pick | Reason |
|---|---|---|
| Text typed into a search or validation field | Debounce | Only the settled value matters |
| Scroll position, resize, drag, mouse move | Throttle | Updates are useful during the motion |
| Sending a progress report during a long action | Throttle | A steady, bounded rate to the server |
| Updates that only change what is painted | requestAnimationFrame | The browser calls it before the next repaint, generally at the display refresh rate, so you never do work for frames nobody sees |
Two practical points for scroll handlers. Register them with { passive: true } when you do not call preventDefault(): MDN documents that this lets the browser start scrolling without waiting for your listener to finish. And for "has this element scrolled into view" questions, an IntersectionObserver (a browser API that calls you back when an element enters or leaves the visible area) removes the need for a scroll handler altogether.
Edge cases and complexity
- Each call is O(1) time and the state is O(1): one timestamp, one timer and the latest arguments.
- The timestamp comes from
Date.now(). A system clock change can move it backwards, which makesremaininglarger thanwait; the timer still fires, so the handler is delayed rather than run too often. A monotonic clock is one that only moves forward and ignores changes to the system time;performance.now()is one, so using it avoids that. thisand the arguments are forwarded, and the trailing call uses the newest pair, not the first one that was queued.cancel()clears the timer and resets the clock so the next call runs immediately; call it when the component that owns the handler goes away.
Running the code
Save the listing as throttle.mjs (the .mjs extension lets Node read import as an ES module) and run it with Node 22, which needs no packages:
node throttle.mjs
Implement an EventEmitter class in JavaScript that lets callers subscribe, subscribe for a single call, unsubscribe and publish. Listeners may be registered with an optional context to use as this, and removal must target exactly the right registration. Explain how you store listener metadata and how you would stop leaks when components forget to unsubscribe.
Sample Answer
An event emitter (also called an event bus or publish/subscribe object: code publishes named events and any number of subscribers react) is a map from event names to lists of listener functions. on appends a registration, emit calls the registrations for that name in order, off removes one, and once registers something that removes itself before its first call. The detail that separates a good answer is what a "registration" is: an object holding the function, the optional context, a once flag and a removed flag. Matching on the function alone cannot tell two registrations of the same function apart, and a flag on the registration is what makes removal during an emit safe.
How listener metadata is stored
| Field | Purpose |
|---|---|
fn | The listener function |
context | The object that becomes this when the listener is called (the emitter itself if none is given, as in Node) |
once | If true, the registration is removed immediately before its call, so a re-entrant emit (an emit of the same event called from inside a listener, while the first emit is still running) cannot run it twice |
removed | Set when the registration is removed, so an emit that already copied the list can skip it |
Removal targets exactly one registration in two ways. on and once return an unsubscribe function bound to that registration object, which is exact even when the same function is registered twice. off(event, fn, context) matches both the function and the context with === and removes the most recent match, the same rule Node documents for removeListener. Lists are copied on every add or remove (copy-on-write: never edit an array in place, build a new one), so emit can iterate over the list it started with (its snapshot) without copying again; adds and removes cost O(n) and emit costs O(n) in the number of listeners for that event.
Implementation with checks
import assert from 'node:assert/strict';
import { EventEmitter as NodeEmitter } from 'node:events';
class EventEmitter {
#listeners = new Map(); // the # makes this a private field: only code inside the class can touch it
// event name -> array of registrations, in order
maxListeners = 10; // warn (once per event) when one event gets more than this
// A registration is the unit of identity: { fn, context, once, removed }.
#add(event, fn, context, once) {
if (typeof fn !== 'function') throw new TypeError('listener must be a function');
const reg = { fn, context, once, removed: false };
const list = this.#listeners.get(event) ?? [];
this.#listeners.set(event, [...list, reg]); // new array: an emit in progress keeps its own copy
if (list.length === this.maxListeners) { // this registration is number maxListeners + 1
console.warn(`possible leak: ${list.length + 1} listeners for "${String(event)}"`);
}
return () => this.#remove(event, reg); // unsubscribe handle for exactly this registration
}
on(event, fn, context) { return this.#add(event, fn, context, false); }
once(event, fn, context) { return this.#add(event, fn, context, true); }
#remove(event, reg) {
if (reg.removed) return false; // calling an unsubscribe twice is harmless
reg.removed = true; // an emit that already copied the list checks this flag
const rest = (this.#listeners.get(event) ?? []).filter((r) => r !== reg);
if (rest.length) this.#listeners.set(event, rest);
else this.#listeners.delete(event); // no empty arrays left behind
return true;
}
// Removes ONE registration whose fn AND context both match (the most recent one).
off(event, fn, context) {
const list = this.#listeners.get(event) ?? [];
for (let i = list.length - 1; i >= 0; i--) {
if (list[i].fn === fn && list[i].context === context) return this.#remove(event, list[i]);
}
return false;
}
// Everything one owner registered, for a component's teardown.
offAll(context) {
for (const [event, list] of [...this.#listeners]) {
for (const reg of list) if (reg.context === context) this.#remove(event, reg);
}
}
emit(event, ...args) {
const snapshot = this.#listeners.get(event) ?? [];
for (const reg of snapshot) {
if (reg.removed) continue; // removed by an earlier listener in this very emit
if (reg.once) this.#remove(event, reg); // before the call, so a re-entrant emit cannot run it twice
reg.fn.apply(reg.context === undefined ? this : reg.context, args);
}
return snapshot.length > 0;
}
listenerCount(event) { return (this.#listeners.get(event) ?? []).length; }
eventNames() { return [...this.#listeners.keys()]; }
}
const log = [];
// 1. Order, arguments, return value.
{
const e = new EventEmitter(); const seen = [];
e.on('x', (a, b) => seen.push(`1:${a}${b}`)); e.on('x', (a) => seen.push(`2:${a}`));
assert.equal(e.emit('x', 'p', 'q'), true); assert.equal(e.emit('none'), false);
assert.deepEqual(seen, ['1:pq', '2:p']);
}
// 2. Context becomes `this`; without one, `this` is the emitter.
{
const e = new EventEmitter(); const ctx = { name: 'widget' }; const who = [];
e.on('x', function () { who.push(this === ctx); }, ctx);
e.on('x', function () { who.push(this === e); });
e.emit('x'); assert.deepEqual(who, [true, true]);
}
// 3. once, and removing a once registration by its original function.
{
const e = new EventEmitter(); let n = 0; const f = () => n++;
e.once('x', f); e.emit('x'); e.emit('x'); assert.equal(n, 1);
e.once('x', f); e.off('x', f); e.emit('x'); assert.equal(n, 1);
}
// 4. Exact removal: same function, different contexts; duplicates; unsubscribe handle.
{
const e = new EventEmitter(); const a = { id: 'A' }, b = { id: 'B' }; const hits = [];
const f = function () { hits.push(this.id); };
e.on('x', f, a); e.on('x', f, b);
e.off('x', f, a); e.emit('x'); assert.deepEqual(hits, ['B']);
const un1 = e.on('y', f, a), un2 = e.on('y', f, a); // identical registrations
un1(); assert.equal(e.listenerCount('y'), 1); un1(); assert.equal(e.listenerCount('y'), 1);
un2(); assert.equal(e.listenerCount('y'), 0);
assert.equal(e.off('x', f, undefined), false, 'no registration has an undefined context');
log.push('exact removal ok: off(fn, ctxA) left only B; the handle removes just its own registration');
}
// 5. A listener unsubscribing itself during emit must not make others skip.
{
const e = new EventEmitter(); const order = []; let offA;
offA = e.on('x', () => { order.push('A'); offA(); });
e.on('x', () => order.push('B')); e.on('x', () => order.push('C'));
e.emit('x'); e.emit('x');
log.push(`self-unsubscribe emit1+emit2 -> ${order}`);
assert.deepEqual(order, ['A', 'B', 'C', 'B', 'C']);
}
// 6. Removing a LATER listener, or adding one, during emit.
{
const e = new EventEmitter(); const order = [];
const b = () => order.push('B');
e.on('x', () => { order.push('A'); e.off('x', b); e.on('x', () => order.push('late')); });
e.on('x', b);
e.emit('x');
const n = new NodeEmitter(); const nodeOrder = [];
const nb = () => nodeOrder.push('B');
n.on('x', () => { nodeOrder.push('A'); n.off('x', nb); }); n.on('x', nb);
n.emit('x');
log.push(`removed-in-emit this emitter: ${order} | Node EventEmitter: ${nodeOrder}`);
assert.deepEqual(order, ['A']); assert.deepEqual(nodeOrder, ['A', 'B']);
}
// 6b. off removes ONE registration per call, the most recent match (Node's documented rule).
{
const e = new EventEmitter(); let n = 0; const f = () => n++;
e.on('x', f); e.once('x', f); // the once registration is the most recent
e.off('x', f);
e.emit('x'); e.emit('x');
assert.equal(n, 2, 'the on() registration survived and ran on both emits');
assert.equal(e.listenerCount('x'), 1);
}
// 6c. A listener added during an emit does not run until the next emit.
{
const e = new EventEmitter(); const order = [];
e.on('x', () => { order.push('A'); if (order.length === 1) e.on('x', () => order.push('late')); });
e.emit('x'); assert.deepEqual(order, ['A']);
e.emit('x'); assert.deepEqual(order, ['A', 'A', 'late']);
}
// 7. Leaks: components that never unsubscribe.
{
const warnings = []; const realWarn = console.warn; console.warn = (m) => warnings.push(m);
const bus = new EventEmitter();
const components = Array.from({ length: 12 }, (_, i) => ({ id: i }));
for (const c of components) bus.on('theme', function () {}, c);
console.warn = realWarn;
assert.equal(warnings.length, 1);
log.push(`leak warning ${warnings[0]}`);
for (const c of components) bus.offAll(c); // what a teardown hook calls
log.push(`after teardown listeners=${bus.listenerCount('theme')} eventNames=${JSON.stringify(bus.eventNames())}`);
assert.equal(bus.listenerCount('theme'), 0); assert.deepEqual(bus.eventNames(), []);
}
console.log(log.join('\n'));
Run in a node:22 container, it prints:
exact removal ok: off(fn, ctxA) left only B; the handle removes just its own registration
self-unsubscribe emit1+emit2 -> A,B,C,B,C
removed-in-emit this emitter: A | Node EventEmitter: A,B
leak warning possible leak: 11 listeners for "theme"
after teardown listeners=0 eventNames=[]
The self-unsubscribe pitfall
Take listeners [A, B, C]. A loop over the live array visits index 0 (A); if A removes itself the array becomes [B, C], index 1 is now C and B is skipped. This emitter avoids that because emit iterates a snapshot (the array as it was when the emit began) and removal builds a new array instead of editing that one. Here listener A removes itself on its first call, and the output shows A, B, C on the first emit and B, C on the second: nobody was skipped. Two policies for removals and additions during an emit are in use, and the output shows both:
- This emitter (and DOM
EventTarget): a listener removed by an earlier listener in the same emit is not called, because the loop checks theremovedflag. The DOM specification's dispatch step iterates only over listeners "whose removed is false" and notes that removal still has an effect on the cloned list. Listeners added during the emit do not run until the next emit. - Node's
EventEmitter: all listeners attached when the emit started are called, even if removed meanwhile. Its documentation says removals during an emit do not affect the emit in progress, and the printedA,Bfor Node confirms it.
The DOM policy is the one to choose for UI code: a component that has just unmounted should not receive one more call.
Stopping leaks when components forget to unsubscribe
The emitter holds a strong reference (one that keeps its target from being garbage collected, the automatic reclaiming of memory nobody can reach any more) to every fn, and each fn closes over its component's props, state and DOM nodes, so a forgotten registration keeps the whole component alive for as long as the emitter lives. Layered defences:
- Make correct usage the easy path. Because
onreturns the unsubscribe function, a React effect can return it directly as its cleanup. Thecontextargument plusoffAll(context)lets a component or class remove everything it registered in one teardown call, which the last test uses after twelve registrations. - Detect it. Warn when one event passes a count threshold; the test shows the warning at the 11th registration, the same idea as Node's default of 10 listeners per event. A growing count in development is the signal that some component forgot to clean up.
- Bound lifetimes. Use
oncefor one-shot reactions, and consider accepting anAbortSignal(the browser object used to cancel work) as an option so a whole group of registrations ends when one signal aborts. - Clean up empty entries. The emitter deletes an event's key when its last listener goes (
eventNames()is[]after teardown), so event names do not accumulate either.
Weak references to listeners are not a safe fix: a listener held only weakly can be collected while still intended, since garbage collection timing is not something to design behaviour around.
Edge cases to state out loud
emitreturnstruewhen at least one listener was registered, like Node.- An exception in a listener stops the loop and propagates to the
emitcaller, as in Node. If isolation matters, wrap each call intry/catchand rethrow the first error after the loop. - Registering the same function twice calls it twice;
offremoves one registration per call, the most recent match. The test registersonthenoncefor the same function, callsoffonce, and checks that theonregistration survives and runs on both emits. - A listener added during an emit does not run until the next emit, because adding builds a new array; the test checks that
lateappears only on the second emit. - Symbols and strings both work as event names because the lookup is a
Map.
Running the code
Save the listing as emitter.mjs (the .mjs extension lets Node read import as an ES module) and run it with Node 22, which needs no packages:
node emitter.mjs
Unlock Full Question Bank
Get access to all 11 Polyfills and JavaScript Utility Implementation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.