These are the notes for JavaScript Coding Questions, episode 29, interview and placement practice for people who finished the SyntaxPilot JavaScript course. Last episode we used Map and Set. Today is a machine coding round: instead of one tricky function, we build small working modules: an event emitter (on, off, once, emit), a key-value store whose keys expire (a TTL), and unit tests for it with Node's built-in node:test.
Each question follows the same steps: the brief, think out loud, the obvious version, a real failure, why, the fix, every test case.
Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. Test durations like (1.2ms) differ on every run.
What a machine coding round checks
- Time: usually 60-90 minutes, sometimes 2 hours. You build a small module that really runs: an event emitter, a cache, a rate limiter, a to-do app's logic, an autocomplete, a promise pool.
- Ask first. Before typing, agree on the API: the method names, their inputs and outputs, and what happens in odd cases ("what does
getreturn for a missing key?", "can the same listener be added twice?"). - Make it work, including edge cases, with readable names and small methods.
- Prove it works: a few tests, or at least a demo script that prints expected vs actual.
- Explain trade-offs: complexity, memory, what you'd add with more time.
An API (application programming interface) is the set of methods other code calls, with their inputs and outputs. In a machine coding round, a clean API is half the marks.
Q1: An event emitter
Brief. Build a class Emitter with:
on(name, fn): callfnevery time the eventnameis emitted.off(name, fn): stop callingfn.once(name, fn): callfnonly the next time, then remove it automatically.emit(name, ...args): call every listener ofname, in the order they were added, withargs. Returntrueif there were listeners, elsefalse(like Node's).
An event is a named thing that happens ("msg", "click", "data"). A listener (or handler, callback) is the function called when it happens. This pattern is called publish/subscribe (pub/sub): publishers emit, subscribers listen with on. Browsers (addEventListener) and Node (EventEmitter, streams, servers) are built on it.
Real life. A class WhatsApp group: joining is on, the teacher posting is emit, leaving is off, and "tell me just the next message" is once.
...args in a parameter list is a rest parameter: it collects every remaining argument into an array. fn(...args) spreads them back out into a call.
Attempt: once removes itself while forEach is looping
class Emitter {
constructor() { this.events = {}; }
on(name, fn) { (this.events[name] ??= []).push(fn); }
off(name, fn) {
const list = this.events[name] ?? [];
const i = list.findIndex(f => f === fn);
if (i !== -1) list.splice(i, 1);
}
once(name, fn) {
const wrapper = (...args) => { this.off(name, wrapper); fn(...args); };
this.on(name, wrapper);
}
emit(name, ...args) {
(this.events[name] ?? []).forEach(fn => fn(...args));
}
}
const group = new Emitter();
group.once("msg", text => console.log("Asha (once):", text));
group.on("msg", text => console.log("Ravi:", text));
group.on("msg", text => console.log("Neha:", text));
group.emit("msg", "Exam on Monday");
group.emit("msg", "Bring calculators");
Asha (once): Exam on Monday
Neha: Exam on Monday
Ravi: Bring calculators
Neha: Bring calculators
Ravi never got "Exam on Monday".
a ??= b(nullish assignment) setsatobonly ifaisnullorundefined, so(this.events[name] ??= [])creates the array the first time and reuses it after.- Why Ravi was skipped:
forEachwalks the array by position: 0, 1, 2. At position 0, Asha's wrapper ran and spliced itself out of that same array. Ravi moved from position 1 to 0 and Neha from 2 to 1.forEachthen went to position 1: Neha. Ravi was jumped over. - Rule: never change an array while you're looping over it. Loop over a copy.
Fix 1: loop over a copy
class Emitter {
constructor() { this.events = {}; }
on(name, fn) { (this.events[name] ??= []).push(fn); }
off(name, fn) {
const list = this.events[name] ?? [];
const i = list.findIndex(f => f === fn);
if (i !== -1) list.splice(i, 1);
}
once(name, fn) {
const wrapper = (...args) => { this.off(name, wrapper); fn(...args); };
this.on(name, wrapper);
}
emit(name, ...args) {
const list = [...(this.events[name] ?? [])]; // a copy
list.forEach(fn => fn(...args));
return list.length > 0;
}
}
const group = new Emitter();
group.once("msg", text => console.log("Asha (once):", text));
group.on("msg", text => console.log("Ravi:", text));
group.on("msg", text => console.log("Neha:", text));
group.emit("msg", "Exam on Monday");
group.emit("msg", "Bring calculators");
const kabir = text => console.log("Kabir:", text);
group.once("drill", kabir); group.off("drill", kabir);
console.log(group.emit("drill", "Fire drill at 3"), group.emit("nobody"));
Asha (once): Exam on Monday
Ravi: Exam on Monday
Neha: Exam on Monday
Ravi: Bring calculators
Neha: Bring calculators
Kabir: Fire drill at 3
true false
Everyone gets message 1 now. But Kabir unsubscribed and still got the drill, and emit says true.
Why? once stored the wrapper, not kabir. off("drill", kabir) searched for kabir, found nothing, removed nothing.
Fix 2: the wrapper remembers the original
class Emitter {
constructor() { this.events = {}; }
on(name, fn) { (this.events[name] ??= []).push(fn); }
off(name, fn) {
const list = this.events[name] ?? [];
const i = list.findIndex(f => f === fn || f.original === fn);
if (i !== -1) list.splice(i, 1);
}
once(name, fn) {
const wrapper = (...args) => { this.off(name, wrapper); fn(...args); };
wrapper.original = fn;
this.on(name, wrapper);
}
emit(name, ...args) {
const list = [...(this.events[name] ?? [])]; // a copy
list.forEach(fn => fn(...args));
return list.length > 0;
}
}
const group = new Emitter();
group.once("msg", text => console.log("Asha (once):", text));
group.on("msg", text => console.log("Ravi:", text));
group.on("msg", text => console.log("Neha:", text));
group.emit("msg", "Exam on Monday");
group.emit("msg", "Bring calculators");
const kabir = text => console.log("Kabir:", text);
group.once("drill", kabir); group.off("drill", kabir);
console.log(group.emit("drill", "Fire drill at 3"), group.emit("nobody"));
Asha (once): Exam on Monday
Ravi: Exam on Monday
Neha: Exam on Monday
Ravi: Bring calculators
Neha: Bring calculators
false false
Functions are objects in JavaScript, so we can put a property on one: wrapper.original = fn. Node's own EventEmitter does the same thing (it calls the property listener).
Complexity. on: O(1). emit: O(k) for k listeners (copy + call each). off and once's self-removal: O(k) to find the listener.
Questions to ask the interviewer (and our answers)
| Question | Our choice |
|---|---|
Same function added twice with on? |
allowed; it's called twice, off removes one copy (like Node) |
| A listener throws an error? | the error stops emit (like Node); a safer version wraps each call in try/catch |
A listener adds a new listener during emit? |
the new one runs from the next emit (we loop over a copy) |
off for a listener that isn't there? |
does nothing |
Should on return something? |
return this for chaining, or an "unsubscribe" function |
A polished version: chaining and an unsubscribe function
class Emitter {
#events = new Map(); // a private field: only code inside the class can use it
on(name, fn) {
if (!this.#events.has(name)) this.#events.set(name, []);
this.#events.get(name).push(fn);
return () => this.off(name, fn); // call this to unsubscribe
}
off(name, fn) {
const list = this.#events.get(name) ?? [];
const i = list.findIndex(f => f === fn || f.original === fn);
if (i !== -1) list.splice(i, 1);
return this;
}
once(name, fn) {
const wrapper = (...args) => { this.off(name, wrapper); fn(...args); };
wrapper.original = fn;
this.on(name, wrapper);
return this;
}
emit(name, ...args) {
const list = [...(this.#events.get(name) ?? [])];
for (const fn of list) fn(...args);
return list.length > 0;
}
listenerCount(name) { return this.#events.get(name)?.length ?? 0; }
}
const shop = new Emitter();
const stop = shop.on("order", item => console.log("kitchen:", item));
shop.once("order", item => console.log("first order of the day:", item));
shop.emit("order", "masala dosa");
stop();
console.log(shop.emit("order", "idli"), shop.listenerCount("order"));
kitchen: masala dosa
first order of the day: masala dosa
false 0
#events is a private field: code outside the class can't read or change it, so nobody can break the emitter by editing events directly.
Q2: A key-value store with a TTL
Brief. set(key, value, ttl) stores a value for ttl milliseconds; get(key) returns it, or undefined once it has expired or if it was never set. size counts only live keys. Setting a key again gives it a fresh TTL.
TTL = time to live: how long an entry stays valid. Caches, sessions, OTPs, rate limiters and DNS records all use TTLs.
Real life. An OTP: the bank's code works for a short time. Ask for a new one and the new one gets its own fresh time.
Attempt: one setTimeout per key
class TTLStore {
constructor() { this.data = new Map(); }
set(key, value, ttl) {
this.data.set(key, value);
setTimeout(() => this.data.delete(key), ttl);
}
get(key) { return this.data.get(key); }
}
const otp = new TTLStore();
otp.set("asha", "4821", 100);
setTimeout(() => otp.set("asha", "7390", 1000), 50);
setTimeout(() => console.log("at 150 ms:", otp.get("asha")), 150);
at 150 ms: undefined
Asha's new OTP was deleted 900 ms early.
setTimeout(fn, ms)runsfnonce, at leastmsmilliseconds later.- Why? The first timer (100 ms) was still waiting. When it fired, it deleted the key without knowing a new value had been stored there at 50 ms.
- A second problem: pending timers keep Node running. Store a key with a one-hour TTL and the program can't exit for an hour (unless you call
timer.unref()). And a million keys means a million timers.
Fix: store the expiry time and check it on read (lazy expiry)
class TTLStore {
constructor(now = Date.now) { this.now = now; this.data = new Map(); }
set(key, value, ttl) {
this.data.set(key, { value, expiresAt: this.now() + ttl });
}
get(key) {
const entry = this.data.get(key);
if (!entry) return undefined;
if (this.now() > entry.expiresAt) { this.data.delete(key); return undefined; }
return entry.value;
}
get size() {
for (const key of [...this.data.keys()]) this.get(key); // drop expired
return this.data.size;
}
}
const otp = new TTLStore();
otp.set("asha", "4821", 100);
setTimeout(() => otp.set("asha", "7390", 300), 50);
setTimeout(() => console.log("at 150 ms:", otp.get("asha")), 150);
setTimeout(() => console.log("at 400 ms:", otp.get("asha"), otp.size), 400);
at 150 ms: 7390
at 400 ms: undefined 0
Date.now()returns the current time in milliseconds since 1 January 1970. We storeexpiresAt = now + ttl.- Setting a key again replaces the entry and its
expiresAt: no old timer is left behind. - Lazy expiry: an entry is only checked (and deleted) when someone reads it. Redis does this too, plus a background sweep.
get size()is a getter: it's written like a method but read like a property,otp.size. Ours sweeps out expired keys first, so the count is right and memory doesn't fill up with dead entries.- The constructor takes
now, a function that returns the time, defaulting toDate.now. Passing a function in instead of callingDate.now()directly is dependency injection; it lets tests use a fake clock (Q3). [...this.data.keys()]copies the keys before the loop, becausegetmay delete from the Map while we loop (the Q1 lesson again).
Complexity. set, get: O(1). size: O(n). In real systems the sweep runs now and then (say, every minute, or a few random keys at a time), not on every size.
Did you spot the bug? We wrote >. Our eyes and our real-timer test didn't. A test with a fake clock will.
Q3: Test it with node:test and a fake clock
A unit test is a small program that runs one piece of your code with a known input and checks the output. node:test is the test runner built into Node (no packages to install), and node:assert has the checks:
| Function | Passes when |
|---|---|
assert.strictEqual(actual, expected) |
actual === expected |
assert.deepStrictEqual(actual, expected) |
same structure and values (arrays, objects) |
assert.ok(value) |
value is truthy |
assert.throws(fn, ErrorType) |
calling fn throws |
Why not wait for real time in tests? A test that waits 1 second per check is slow, and real timers are never exactly on time, so you can't test "exactly at the TTL". A fake clock is a variable the test moves by hand.
Real life. A quality checker's clipboard: one line per check, a clock she can set by hand, a red cross with "expected vs got" when a check fails.
The tests find the bug
const test = require("node:test");
const assert = require("node:assert");
class TTLStore {
constructor(now = Date.now) { this.now = now; this.data = new Map(); }
set(key, value, ttl) { this.data.set(key, { value, expiresAt: this.now() + ttl }); }
get(key) {
const e = this.data.get(key);
if (!e) return undefined;
if (this.now() > e.expiresAt) { this.data.delete(key); return undefined; }
return e.value;
}
}
let t = 0; // a fake clock: the test moves time by hand
const store = () => { t = 0; return new TTLStore(() => t); };
test("there before the ttl", () => {
const s = store(); s.set("asha", "4821", 1000); t = 999;
assert.strictEqual(s.get("asha"), "4821");
});
test("gone exactly at the ttl", () => {
const s = store(); s.set("asha", "4821", 1000); t = 1000;
assert.strictEqual(s.get("asha"), undefined);
});
test("set again restarts the clock", () => {
const s = store(); s.set("asha", "4821", 100); t = 50;
s.set("asha", "7390", 1000); t = 150;
assert.strictEqual(s.get("asha"), "7390");
});
✔ there before the ttl (0.832416ms)
✖ gone exactly at the ttl (0.993739ms)
✔ set again restarts the clock (0.180515ms)
ℹ tests 3
ℹ suites 0
ℹ pass 2
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 7.999727
✖ failing tests:
test at main.js:19:1
✖ gone exactly at the ttl (0.993739ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ '4821'
- undefined
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: '4821',
expected: undefined,
operator: 'strictEqual',
diff: 'simple'
}
(The stack trace lines under the error are shortened here.) The program's exit code is 1 when a test fails, so a CI system marks the build red.
Why? At exactly t = 1000, expiresAt is also 1000, and 1000 > 1000 is false. The OTP lived one millisecond too long. This is a boundary bug (an off-by-one error): the kind that shows up only at the exact edge, which a real-timer test can never hit on purpose.
Fix: >=
const test = require("node:test");
const assert = require("node:assert");
class TTLStore {
constructor(now = Date.now) { this.now = now; this.data = new Map(); }
set(key, value, ttl) { this.data.set(key, { value, expiresAt: this.now() + ttl }); }
get(key) {
const e = this.data.get(key);
if (!e) return undefined;
if (this.now() >= e.expiresAt) { this.data.delete(key); return undefined; }
return e.value;
}
}
let t = 0; // a fake clock: the test moves time by hand
const store = () => { t = 0; return new TTLStore(() => t); };
test("there before the ttl", () => {
const s = store(); s.set("asha", "4821", 1000); t = 999;
assert.strictEqual(s.get("asha"), "4821");
});
test("gone exactly at the ttl", () => {
const s = store(); s.set("asha", "4821", 1000); t = 1000;
assert.strictEqual(s.get("asha"), undefined);
});
test("set again restarts the clock", () => {
const s = store(); s.set("asha", "4821", 100); t = 50;
s.set("asha", "7390", 1000); t = 150;
assert.strictEqual(s.get("asha"), "7390");
});
✔ there before the ttl (0.710863ms)
✔ gone exactly at the ttl (0.1568ms)
✔ set again restarts the clock (0.117078ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 7.119936
Pass 3, fail 0, in milliseconds.
In a real project
Keep the code and the tests in separate files, and let Node find the tests:
ttl-store.js module.exports = { TTLStore };
ttl-store.test.js const { TTLStore } = require("./ttl-store"); ...tests...
node --test runs every *.test.js file (and files in a test/ folder)
describe("TTLStore", () => { ... }) groups related tests, and node:test also has mock.timers to fake setTimeout and Date for code that uses them directly.
Testing the emitter too
const test = require("node:test");
const assert = require("node:assert");
class Emitter {
constructor() { this.events = {}; }
on(name, fn) { (this.events[name] ??= []).push(fn); }
off(name, fn) {
const list = this.events[name] ?? [];
const i = list.findIndex(f => f === fn || f.original === fn);
if (i !== -1) list.splice(i, 1);
}
once(name, fn) {
const wrapper = (...args) => { this.off(name, wrapper); fn(...args); };
wrapper.original = fn;
this.on(name, wrapper);
}
emit(name, ...args) {
const list = [...(this.events[name] ?? [])];
list.forEach(fn => fn(...args));
return list.length > 0;
}
}
test("listeners run in order with the arguments", () => {
const e = new Emitter(), got = [];
e.on("msg", t => got.push("A:" + t));
e.on("msg", t => got.push("B:" + t));
e.emit("msg", "hi");
assert.deepStrictEqual(got, ["A:hi", "B:hi"]);
});
test("once runs one time and does not skip the next listener", () => {
const e = new Emitter(), got = [];
e.once("msg", () => got.push("once"));
e.on("msg", () => got.push("always"));
e.emit("msg"); e.emit("msg");
assert.deepStrictEqual(got, ["once", "always", "always"]);
});
test("off removes a once listener by its original function", () => {
const e = new Emitter(), got = [];
const fn = () => got.push("x");
e.once("drill", fn); e.off("drill", fn);
assert.strictEqual(e.emit("drill"), false);
assert.deepStrictEqual(got, []);
});
✔ listeners run in order with the arguments (2.583892ms)
✔ once runs one time and does not skip the next listener (0.332162ms)
✔ off removes a once listener by its original function (0.215923ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 13.566884
assert.deepStrictEqual compares arrays item by item; strictEqual would compare two different array objects and fail.
Common mistakes (and the exact outputs)
| Mistake | Code | What you see | Why | Fix |
|---|---|---|---|---|
| Changing the listener array while looping it | forEach over this.events[name] while once splices |
Ravi misses Exam on Monday |
items shift left under the loop | loop over a copy: [...list] |
off with the original function after once |
group.once("drill", kabir); group.off("drill", kabir) |
Kabir: Fire drill at 3 |
once stored a wrapper |
wrapper.original = fn, match it in off |
off with a new arrow function |
e.on("x", () => f()); e.off("x", () => f()) |
still called | two arrows are two different functions | keep the function in a variable |
One setTimeout per key |
setTimeout(() => this.data.delete(key), ttl) |
at 150 ms: undefined |
the old timer deletes the new value | store expiresAt, check on read |
> at the boundary |
this.now() > e.expiresAt |
AssertionError ... + '4821' - undefined |
alive at exactly the TTL | >= |
strictEqual on arrays |
assert.strictEqual([1], [1]) |
AssertionError |
two different objects | assert.deepStrictEqual |
| Tests that share state | one store for all tests | a test passes or fails depending on order | leftovers from earlier tests | a fresh store per test (store()) |
The arrow-function off trap, for real:
const listeners = [];
const on = fn => listeners.push(fn);
const off = fn => { const i = listeners.indexOf(fn); if (i !== -1) listeners.splice(i, 1); };
on(() => console.log("hello"));
off(() => console.log("hello"));
console.log("after off with a new arrow:", listeners.length);
const greet = () => console.log("hello");
on(greet); off(greet);
console.log("after off with the same function:", listeners.length);
after off with a new arrow: 1
after off with the same function: 1
The first off removed nothing: two arrows with the same text are two different functions, so the list still holds 1. The second line is still 1 because that first arrow is still there; greet was added and then really removed.
The deepStrictEqual trap, for real:
const assert = require("node:assert");
try { assert.strictEqual([1, 2], [1, 2]); } catch (e) { console.log(e.name + ":", e.message.split("\n")[0]); }
assert.deepStrictEqual([1, 2], [1, 2]);
console.log("deepStrictEqual passed");
AssertionError: Values have same structure but are not reference-equal:
deepStrictEqual passed
Mini project: a rate limiter
Another machine coding favourite: allow at most limit calls per user in any windowMs window (a sliding window). Same ideas: a Map per user, a fake clock for tests.
class RateLimiter {
constructor(limit, windowMs, now = Date.now) { this.limit = limit; this.windowMs = windowMs; this.now = now; this.hits = new Map(); }
allow(user) {
const t = this.now();
const recent = (this.hits.get(user) ?? []).filter(time => t - time < this.windowMs);
if (recent.length >= this.limit) { this.hits.set(user, recent); return false; }
recent.push(t);
this.hits.set(user, recent);
return true;
}
}
let t = 0;
const otpRequests = new RateLimiter(3, 60000, () => t); // 3 OTPs per minute
const out = [];
for (const at of [0, 10000, 20000, 30000, 59999, 60000, 70000]) { t = at; out.push(`${at / 1000}s:${otpRequests.allow("asha")}`); }
console.log(out.join(" "));
console.log("ravi:", otpRequests.allow("ravi"));
0s:true 10s:true 20s:true 30s:false 59.999s:false 60s:true 70s:true
ravi: true
At 30 s and 59.999 s Asha has already used 3 in the last minute. At 60 s, the request from 0 s is exactly a minute old and drops out of the window, so one more is allowed; at 70 s, the 10 s request drops out. Each call is O(limit).
Your turn: waitFor(name), an event as a promise (solution)
Add waitFor(name): it returns a promise that resolves with the first argument of the next emit of name.
class Emitter {
constructor() { this.events = {}; }
on(name, fn) { (this.events[name] ??= []).push(fn); }
off(name, fn) {
const list = this.events[name] ?? [];
const i = list.findIndex(f => f === fn || f.original === fn);
if (i !== -1) list.splice(i, 1);
}
once(name, fn) {
const wrapper = (...args) => { this.off(name, wrapper); fn(...args); };
wrapper.original = fn;
this.on(name, wrapper);
}
emit(name, ...args) {
const list = [...(this.events[name] ?? [])];
list.forEach(fn => fn(...args));
return list.length > 0;
}
waitFor(name) {
return new Promise(resolve => this.once(name, resolve));
}
}
const group = new Emitter();
(async () => {
console.log("waiting for the result...");
const text = await group.waitFor("result");
console.log("got:", text);
})();
setTimeout(() => group.emit("result", "Asha passed!"), 100);
setTimeout(() => console.log("listeners left:", group.events.result.length), 200);
waiting for the result...
got: Asha passed!
listeners left: 0
resolve is itself a function, so it can be the once listener directly: the first emit calls resolve(text), the promise settles, and once removes the listener. Node has the same thing built in: const [text] = await events.once(emitter, "result") (from require("node:events")). A test for it:
const test = require("node:test");
const assert = require("node:assert");
class Mini {
constructor() { this.fns = []; }
once(fn) { this.fns.push(fn); }
emit(x) { const f = this.fns; this.fns = []; f.forEach(fn => fn(x)); }
waitFor() { return new Promise(resolve => this.once(resolve)); }
}
test("waitFor resolves with the next emit", async () => {
const e = new Mini();
const p = e.waitFor();
e.emit("hello");
assert.strictEqual(await p, "hello");
assert.strictEqual(e.fns.length, 0);
});
✔ waitFor resolves with the next emit (0.772378ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 6.95623
A test function can be async; the runner waits for its promise.
Practice questions (with solutions)
1. A wildcard listener: on("*", fn) hears every event, called as fn(name, ...args).
Solution
class Emitter {
constructor() { this.events = {}; }
on(name, fn) { (this.events[name] ??= []).push(fn); }
emit(name, ...args) {
const list = [...(this.events[name] ?? [])];
const all = [...(this.events["*"] ?? [])];
list.forEach(fn => fn(...args));
all.forEach(fn => fn(name, ...args));
return list.length + all.length > 0;
}
}
const e = new Emitter();
e.on("*", (name, ...args) => console.log("log:", name, args));
e.on("order", item => console.log("kitchen:", item));
e.emit("order", "poha");
e.emit("payment", 40, "UPI");
kitchen: poha
log: order [ 'poha' ]
log: payment [ 40, 'UPI' ]
2. touch(key, ttl) extends a live key's TTL without changing its value; returns false for a missing or expired key.
Solution
class TTLStore {
constructor(now = Date.now) { this.now = now; this.data = new Map(); }
set(key, value, ttl) { this.data.set(key, { value, expiresAt: this.now() + ttl }); }
get(key) {
const e = this.data.get(key);
if (!e) return undefined;
if (this.now() >= e.expiresAt) { this.data.delete(key); return undefined; }
return e.value;
}
touch(key, ttl) {
if (this.get(key) === undefined && !this.data.has(key)) return false;
this.data.get(key).expiresAt = this.now() + ttl;
return true;
}
}
let t = 0;
const s = new TTLStore(() => t);
s.set("session", "asha", 1000);
t = 900; console.log(s.touch("session", 1000));
t = 1500; console.log(s.get("session"));
t = 1900; console.log(s.get("session"), s.touch("session", 1000), s.touch("nobody", 5));
true
asha
undefined false false
get runs first so an expired key is deleted before we check has.
3. A once that also works with emit returning listener results: make emit return an array of what each listener returned.
Solution
class Emitter {
constructor() { this.events = {}; }
on(name, fn) { (this.events[name] ??= []).push(fn); }
emitCollect(name, ...args) {
return [...(this.events[name] ?? [])].map(fn => fn(...args));
}
}
const e = new Emitter();
e.on("price", qty => qty * 15);
e.on("price", qty => qty * 15 * 1.05);
console.log(e.emitCollect("price", 4), e.emitCollect("none"));
[ 60, 63 ] []
4. Write tests for RateLimiter (the mini project): the 4th call in a window is refused, and a call is allowed again once the oldest drops out.
Solution
const test = require("node:test");
const assert = require("node:assert");
class RateLimiter {
constructor(limit, windowMs, now = Date.now) { this.limit = limit; this.windowMs = windowMs; this.now = now; this.hits = new Map(); }
allow(user) {
const t = this.now();
const recent = (this.hits.get(user) ?? []).filter(time => t - time < this.windowMs);
if (recent.length >= this.limit) { this.hits.set(user, recent); return false; }
recent.push(t); this.hits.set(user, recent); return true;
}
}
test("the 4th call in a minute is refused", () => {
let t = 0; const r = new RateLimiter(3, 60000, () => t);
assert.deepStrictEqual([0, 1, 2, 3].map(s => { t = s * 1000; return r.allow("asha"); }), [true, true, true, false]);
});
test("allowed again when the oldest call is a minute old", () => {
let t = 0; const r = new RateLimiter(3, 60000, () => t);
r.allow("a"); t = 1; r.allow("a"); t = 2; r.allow("a");
t = 60000; assert.strictEqual(r.allow("a"), true);
});
test("users are counted separately", () => {
let t = 0; const r = new RateLimiter(1, 60000, () => t);
assert.strictEqual(r.allow("asha"), true);
assert.strictEqual(r.allow("ravi"), true);
});
✔ the 4th call in a minute is refused (1.623651ms)
✔ allowed again when the oldest call is a minute old (0.200254ms)
✔ users are counted separately (0.110679ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 10.573089
Quick quiz
const { EventEmitter } = require("node:events");
const e = new EventEmitter();
e.on("x", () => console.log("A"));
e.once("x", () => console.log("B"));
e.emit("x"); e.emit("x");
console.log(e.listenerCount("x"));
Answer
A
B
A
1
A: A B A, then 1. Node's EventEmitter calls listeners in the order they were added; B was once, so the second emit calls only A, and one listener is left.
Interview questions
- Why loop over a copy in
emit? Listeners may add or remove listeners (aonceremoves itself). Changing an array while iterating it skips or repeats items. - How does
offremove aoncelistener?oncestores a wrapper; give the wrapper a reference to the original (wrapper.original = fn) and match either inoff. - Why not one
setTimeoutper key in a TTL store? An old timer can delete a newer value, timers keep the process alive, and millions of timers waste memory. StoreexpiresAtand check on read. - What is lazy expiry? What's its downside? Checking expiry only when a key is read. Keys nobody reads stay in memory, so add a periodic sweep.
- How do you test time-based code without waiting? Inject the clock (
nowfunction) and use a fake one in tests, or usemock.timersfromnode:test. strictEqualvsdeepStrictEqual?===vs comparing structure and values.- What would you add with more time? Error handling per listener, a max-listeners warning,
prependListener, typed events, a sweep timer withunref(), and an LRU size limit on the store. - What does the machine coding round test that a DSA round doesn't? API design, readable structure, edge cases, testing, and working software under time pressure.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Machine coding round | An interview round where you build a small working module in 60-90 minutes | an event emitter |
| API | The methods other code calls, with their inputs and outputs | on, off, once, emit |
| Event | A named thing that happens | "msg", "click" |
| Listener / handler / callback | A function called when an event happens | text => console.log(text) |
| Event emitter | An object that keeps listeners per event name and calls them on emit |
Node's EventEmitter |
| Publish/subscribe (pub/sub) | Publishers emit events; subscribers listen, without knowing each other | a WhatsApp group |
| Wrapper | A function that calls another function, adding something before or after | once's self-removing wrapper |
| Rest parameter / spread | ...args collects arguments into an array / spreads an array into a call |
fn(...args) |
??= |
Assign only if the left side is null or undefined |
(obj[k] ??= []) |
| Private field | A #name field only the class's own code can use |
#events |
| TTL (time to live) | How long an entry stays valid | an OTP valid for a few seconds |
Date.now() |
The current time in milliseconds since 1 Jan 1970 | expiresAt = Date.now() + ttl |
setTimeout |
Run a function once, at least ms milliseconds later |
setTimeout(fn, 100) |
| Lazy expiry | Check whether an entry expired only when it's read | get deletes expired keys |
| Getter | A method read like a property | get size() → store.size |
| Dependency injection | Passing in what a class depends on instead of hard-coding it | new TTLStore(() => t) |
| Fake clock | A clock the test sets by hand | let t = 0; ... t = 1000; |
| Unit test | A small program checking one piece of code with a known input | test("gone at the ttl", ...) |
node:test |
Node's built-in test runner | const test = require("node:test") |
| Assertion | A check that throws if it's false | assert.strictEqual(a, b) |
AssertionError |
The error a failed assertion throws, with actual vs expected | + '4821' - undefined |
| Boundary / off-by-one bug | A bug at the exact edge of a range | > instead of >= |
| Sliding window | "In the last N milliseconds", moving with the current time | the rate limiter |
| Exit code | The number a program ends with; non-zero means failure | 1 when a test fails |
Summary
- A machine coding round wants a clear API, working code with edge cases, readable structure, and tests.
- Event emitter:
onpushes,emitloops over a copy,oncewraps and removes itself, and the wrapper remembersoriginalsooffcan find it. - TTL store: no timer per key; store
expiresAtand check it on read (lazy expiry); sweep now and then; inject the clock. node:test+node:assertand a fake clock test time without waiting, and found our>vs>=boundary bug.- Next episode, the last of the series: tricky output questions:
==vs===,typeof null, NaN, the TDZ,[] + {},0.1 + 0.2,varin loops,this.