Appearance
Write It Yourself
92. Implement debounce.
The short answer
A debounced function waits until calls stop for a given time, and then runs once with the latest arguments. Every new call cancels the pending timer and starts a new one. It is used for search-as-you-type, resizing and autosave, where you only care about the final value after the user pauses. The implementation keeps the timer ID in a closure, clears it on each call, and sets a new timeout.
ts
function debounce<A extends unknown[]>(fn: (...args: A) => void, waitMs: number) {
let timer: ReturnType<typeof setTimeout> | undefined // (1)
const debounced = (...args: A) => {
clearTimeout(timer) // (2)
timer = setTimeout(() => { // (3)
timer = undefined
fn(...args) // (4)
}, waitMs)
}
debounced.cancel = () => { // (5)
clearTimeout(timer)
timer = undefined
}
return debounced
}
const searchProducts = debounce((q: string) => fetch(`/api/search?q=${encodeURIComponent(q)}`), 300)
input.addEventListener('input', (e) => searchProducts((e.target as HTMLInputElement).value))- The timer lives in a closure, shared by every call to
debounced(question 11). - Each call cancels the pending run.
clearTimeout(undefined)is harmless, so no check is needed. - Start a fresh wait.
- Run with the latest arguments once nobody has called for
waitMs. - A
cancelmethod, so a component can stop a pending call when it unmounts.
Typing "trainers" fires 8 input events, but only one search request is sent, 300 ms after the last key.
Follow-up questions to be ready for:
- Leading edge: run on the first call, then ignore calls until things are quiet. Useful for a "submit" button to stop double clicks. Add a
leadingoption that callsfnwhentimerisundefined. this: the arrow function above ignoresthis. To support methods, writefunction (this: unknown, ...args)and callfn.apply(this, args).- Returning a value: a debounced call cannot return the result directly, because it may run later. Return a promise if the caller needs it.
93. Implement throttle.
The short answer
A throttled function runs at most once in each time window, however often it is called. The first call runs straight away; calls during the window are not run immediately, but the last one is remembered and run when the window ends, so the final state is never lost. It is used for scroll and mouse-move handlers, progress updates and rate-limiting outgoing requests.
ts
function throttle<A extends unknown[]>(fn: (...args: A) => void, windowMs: number) {
let lastRun = 0 // (1)
let timer: ReturnType<typeof setTimeout> | undefined
let pendingArgs: A | undefined
return (...args: A) => {
const remaining = windowMs - (Date.now() - lastRun) // (2)
if (remaining <= 0) { // (3)
clearTimeout(timer)
timer = undefined
lastRun = Date.now()
fn(...args)
return
}
pendingArgs = args // (4)
if (!timer) {
timer = setTimeout(() => { // (5)
lastRun = Date.now()
timer = undefined
fn(...pendingArgs!)
}, remaining)
}
}
}
const saveScrollPosition = throttle((y: number) => sessionStorage.setItem('y', String(y)), 500)
window.addEventListener('scroll', () => saveScrollPosition(window.scrollY))- When the function last ran. Starting at
0means the very first call runs immediately. - How long until the window is over.
- Window over: run now, and cancel any scheduled trailing run, because this one replaces it.
- Inside the window: remember the latest arguments.
- Schedule one trailing run for the end of the window, if one is not already scheduled. It uses the most recent arguments, so the final scroll position is always saved.
Debounce versus throttle, the follow-up that always comes:
| Debounce | Throttle | |
|---|---|---|
| Runs | Once, after calls stop | Regularly, at most once per window |
| During a long burst | Never, until it ends | Every window |
| Good for | Search box, autosave, resize end | Scroll, drag, live progress |
94. Implement memoize.
The short answer
A memoised function remembers results by their arguments and returns the stored result when called again with the same arguments. Build a key from the arguments, check a Map, compute and store on a miss. A production version also handles async functions by caching the promise and removing it on failure, and limits how big the cache can grow.
ts
function memoize<A extends unknown[], R>(
fn: (...args: A) => R,
keyOf: (...args: A) => string = (...args) => JSON.stringify(args), // (1)
) {
const cache = new Map<string, R>()
return (...args: A): R => {
const key = keyOf(...args)
if (cache.has(key)) return cache.get(key)! // (2)
const result = fn(...args)
cache.set(key, result)
if (result instanceof Promise) { // (3)
result.catch(() => cache.delete(key))
}
return result
}
}
const getExchangeRate = memoize((from: string, to: string) =>
fetch(`/api/rates?from=${from}&to=${to}`).then((r) => r.json()),
)
await Promise.all([getExchangeRate('GBP', 'EUR'), getExchangeRate('GBP', 'EUR')]) // one request- The key builder.
JSON.stringifyworks for simple arguments. Allow a custom one for objects, where only anidmight matter. has, not a truthiness check, so cached results like0,''ornullare still returned from the cache.- For async functions, cache the promise. Two callers at the same moment share one request. If it fails, remove it, otherwise the failure is cached for ever.
Mention in the interview: memoise only pure functions (question 19), and bound the cache, for example with the LRU from question 102, or entries never leave memory.
95. Implement curry.
The short answer
curry(fn) returns a function that collects arguments across calls until it has as many as fn expects, which it reads from fn.length, and then calls fn with all of them. Each partial call returns a new function that remembers the arguments so far. The trick is a recursive inner function that either runs fn or returns another collector.
ts
function curry(fn: (...args: any[]) => any) {
return function curried(...args: any[]): any {
if (args.length >= fn.length) return fn(...args) // (1)
return (...more: any[]) => curried(...args, ...more) // (2)
}
}
const price = (base: number, taxRate: number, discount: number) =>
base * (1 + taxRate) - discount
const curriedPrice = curry(price)
curriedPrice(100)(0.2)(5) // 115
curriedPrice(100, 0.2)(5) // 115
const ukPrice = curriedPrice(100, 0.2)
ukPrice(10) // 110- Enough arguments collected: call the original function.
- Not enough: return a function that adds the new arguments to the ones already collected and tries again.
Edge cases worth mentioning: fn.length does not count parameters with default values or a rest parameter, so curry cannot know how many such a function expects. Typing a fully generic curry precisely in TypeScript needs advanced recursive types; in an interview, any with a note is accepted.
96. Implement deep clone.
The short answer
Walk the value recursively: return primitives as they are, and for objects create a new container of the same kind, then copy each property by cloning it too. Handle the special built-ins, such as Date, Map, Set and arrays, separately. Keep a WeakMap from original objects to their copies, so circular references and shared objects are copied once and do not cause an endless loop. In real code, use structuredClone.
ts
function deepClone<T>(value: T, seen = new WeakMap<object, unknown>()): T {
if (value === null || typeof value !== 'object') return value // (1)
if (seen.has(value)) return seen.get(value) as T // (2)
if (value instanceof Date) return new Date(value.getTime()) as T // (3)
if (value instanceof Map) {
const copy = new Map()
seen.set(value, copy)
for (const [k, v] of value) copy.set(deepClone(k, seen), deepClone(v, seen))
return copy as T
}
if (value instanceof Set) {
const copy = new Set()
seen.set(value, copy)
for (const v of value) copy.add(deepClone(v, seen))
return copy as T
}
const copy = (Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value))) as Record<PropertyKey, unknown> // (4)
seen.set(value, copy) // (5)
for (const key of Reflect.ownKeys(value)) { // (6)
copy[key] = deepClone((value as Record<PropertyKey, unknown>)[key], seen)
}
return copy as T
}
const order = { id: 'A12', items: [{ sku: 'tea' }], placedAt: new Date() } as any
order.self = order // a cycle
const copy = deepClone(order)
copy.items[0].sku = 'mug'
console.log(order.items[0].sku) // 'tea'
console.log(copy.self === copy) // true: cycle preserved- Primitives and functions are returned as they are. Functions are shared, not copied.
- Already copied? Return that copy. This is what breaks cycles.
- Dates need a new
Date, or the clone would be an empty object. - A new container of the same kind, keeping the prototype so class instances stay instances.
- Register the copy before recursing, so a cycle that leads back here finds it.
Reflect.ownKeysincludes symbol keys, whichObject.keyswould miss.
What to say about real projects: structuredClone covers this, faster and more completely, including typed arrays and errors. It refuses functions and class methods, which is often what you want for data.
97. Flatten a nested array.
The short answer
Go through the array, and for each item that is itself an array, flatten it and add its items; otherwise add the item. A recursive version is shortest. An iterative version uses a stack, which avoids stack overflow on very deep nesting. A depth parameter controls how many levels to flatten. In real code, array.flat(depth) does this, and flat(Infinity) flattens everything.
ts
function flatten<T>(items: unknown[], depth = Infinity): T[] { // recursive
const out: T[] = []
for (const item of items) {
if (Array.isArray(item) && depth > 0) out.push(...flatten<T>(item, depth - 1))
else out.push(item as T)
}
return out
}
function flattenIterative<T>(items: unknown[]): T[] { // no recursion
const stack = [...items]
const out: T[] = []
while (stack.length) {
const next = stack.pop() // (1)
if (Array.isArray(next)) stack.push(...next) // (2)
else out.push(next as T)
}
return out.reverse() // (3)
}
flatten([1, [2, [3, [4]]]]) // [1, 2, 3, 4]
flatten([1, [2, [3, [4]]]], 1) // [1, 2, [3, [4]]]- Take the last item from the stack.
- An array goes back on the stack as its items.
- Items come out in reverse order, because a stack is last in, first out, so reverse once at the end.
Complexity: each item is visited once, so O(n) time for n items in total. out.push(...big) can hit the argument limit for very large inner arrays; pushing in a loop avoids that.
98. Implement Promise.all.
The short answer
Return a new promise. Wrap every input in Promise.resolve, so plain values work too, and attach a handler to each. Store each result at its own index, so the order matches the input and not the finishing order. Count how many have finished, and resolve with the array when the count reaches the total. Reject immediately when any input rejects. An empty input resolves at once with an empty array.
ts
function promiseAll<T>(inputs: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>[]> {
const list = Array.from(inputs) // (1)
return new Promise((resolve, reject) => {
const results = new Array<Awaited<T>>(list.length)
let remaining = list.length
if (remaining === 0) return resolve(results) // (2)
list.forEach((input, index) => {
Promise.resolve(input).then( // (3)
(value) => {
results[index] = value as Awaited<T> // (4)
remaining -= 1
if (remaining === 0) resolve(results) // (5)
},
reject, // (6)
)
})
})
}
await promiseAll([getProduct('p1'), 42, getStock('p1')]) // [product, 42, stock]- Accept any iterable, as the real one does, by copying it into an array.
- Empty input resolves immediately, otherwise the promise would never settle.
Promise.resolvewraps plain values, so42works like an already-fulfilled promise.- Store by index, not with
push, so a fast third promise does not land in position one. - Resolve only when every input has finished.
- The first rejection rejects the whole thing. Later calls to
rejectorresolveare ignored, because a promise settles only once (question 52).
Common mistakes interviewers look for: using push and getting the order wrong; checking results.length === list.length, which is wrong because new Array(n) already has length n; and forgetting the empty case. A natural follow-up is allSettled: never reject, and store { status: 'fulfilled', value } or { status: 'rejected', reason } at each index.
99. Run async tasks with a concurrency limit.
The short answer
Start a fixed number of workers, say 5, and have each worker repeatedly take the next unprocessed item from a shared index, process it with await, and then take another, until none are left. That keeps at most 5 tasks running at once, starts the next task as soon as any finishes, and stores each result at its own index. It is the standard answer for "process 10,000 items without overwhelming the API or database".
ts
async function mapWithLimit<T, R>(
items: T[],
limit: number,
task: (item: T, index: number) => Promise<R>,
): Promise<R[]> {
const results = new Array<R>(items.length)
let next = 0 // (1)
async function worker() {
while (next < items.length) {
const index = next++ // (2)
results[index] = await task(items[index], index) // (3)
}
}
const workers = Array.from({ length: Math.min(limit, items.length) }, () => worker()) // (4)
await Promise.all(workers) // (5)
return results
}
const receipts = await mapWithLimit(orderIds, 5, (id) => sendReceipt(id))- A shared position in the list.
- Take the next item and move the position on. This is safe without locks, because JavaScript runs one piece of code at a time: no two workers can run this line at the same moment.
- Process it, and store the result at its own index, so the order matches the input.
- Start
limitworkers, or fewer if there are fewer items. - Finish when every worker has run out of items.
Follow-ups:
- Errors: as written, the first failure rejects
Promise.all, but the other workers keep going. To stop them, check afailedflag in the loop, or pass anAbortSignal. To collect all outcomes instead, catch insideworkerand store{ ok: false, error }. - Why not batches of 5? Batching waits for the slowest of each 5 before starting the next 5. Workers keep all 5 lanes busy all the time.
- Libraries such as
p-limitdo this in production.
100. Retry a failing async call with exponential backoff.
The short answer
Call the function, and if it fails with an error worth retrying, wait and try again, doubling the wait each time: 200 ms, 400 ms, 800 ms, up to a maximum. Add random jitter to each wait, so many clients that failed at the same moment do not all retry at the same moment. Stop after a fixed number of attempts and rethrow the last error. Only retry errors that might succeed next time, and only operations that are safe to repeat.
ts
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
type RetryOptions = {
retries?: number
baseMs?: number
maxMs?: number
shouldRetry?: (err: unknown) => boolean
}
async function retry<T>(fn: () => Promise<T>, opts: RetryOptions = {}): Promise<T> {
const { retries = 3, baseMs = 200, maxMs = 5_000, shouldRetry = () => true } = opts
for (let attempt = 0; ; attempt++) {
try {
return await fn() // (1)
} catch (err) {
if (attempt >= retries || !shouldRetry(err)) throw err // (2)
const cap = Math.min(maxMs, baseMs * 2 ** attempt) // (3)
await sleep(Math.random() * cap) // (4)
}
}
}
const isTransient = (err: unknown) =>
err instanceof HttpError && (err.status === 429 || err.status >= 500)
const rates = await retry(() => fetchExchangeRates(), { shouldRetry: isTransient })- Try the call.
return awaitis needed so a rejection is caught here (question 54). - Give up when attempts run out, or when the error is not worth retrying.
- Exponential growth: 200, 400, 800, 1,600 ms, capped at 5 seconds.
- Full jitter: wait a random time between 0 and the cap. Without it, a thousand clients that failed together retry together and knock the service down again.
What makes a retry safe:
| Retry | Do not retry |
|---|---|
| Timeouts, connection resets | 400 Bad Request, validation errors |
429 Too Many Requests, respecting Retry-After | 401 or 403 |
502, 503, 504 | 404 for a resource that does not exist |
| Idempotent operations, or ones sent with an idempotency key | A payment with no idempotency key |
Retrying a non-idempotent call, such as charging a card, can do it twice. Retries, backoff and circuit breakers at the system level are covered in the architecture module.
101. Implement a simple EventEmitter.
The short answer
Keep a Map from event name to a list of listener functions. on adds a listener, off removes it, emit calls every listener for that event with the arguments, in order, and once wraps the listener in a function that removes itself before calling it. Copy the list before looping in emit, so a listener that removes itself does not make the loop skip the next one.
ts
type Listener = (...args: any[]) => void
class Emitter {
private listeners = new Map<string, Listener[]>()
on(event: string, fn: Listener) {
const list = this.listeners.get(event) ?? []
list.push(fn)
this.listeners.set(event, list)
return () => this.off(event, fn) // (1)
}
off(event: string, fn: Listener) {
const list = this.listeners.get(event)
if (!list) return
const i = list.indexOf(fn)
if (i !== -1) list.splice(i, 1)
}
once(event: string, fn: Listener) {
const wrapper: Listener = (...args) => {
this.off(event, wrapper) // (2)
fn(...args)
}
return this.on(event, wrapper)
}
emit(event: string, ...args: unknown[]) {
const list = this.listeners.get(event)
if (!list?.length) return false
for (const fn of [...list]) fn(...args) // (3)
return true
}
}
const cart = new Emitter()
const stop = cart.on('item-added', (sku) => console.log('added', sku))
cart.once('item-added', () => console.log('first item!'))
cart.emit('item-added', 'tea') // added tea, first item!
cart.emit('item-added', 'mug') // added mug
stop()- Return an unsubscribe function, a convenient pattern used by many libraries.
onceremoves itself first, so even if the listener throws, it never runs again.- Loop over a copy: if a listener removes itself mid-loop, the next listener is still called.
Follow-ups: typed events with a generic map such as Emitter<{ 'item-added': [sku: string] }>; error handling, where Node.js throws if 'error' is emitted with no listener (question 69); and a maximum listener warning to catch leaks.
102. Implement an LRU cache.
The short answer
An LRU, least recently used, cache holds up to a fixed number of entries and, when full, throws away the entry that was used longest ago. In JavaScript, a Map makes it short, because a Map remembers insertion order: on every read, delete the key and set it again to move it to the newest end; on insert, if the cache is full, delete the first key, which is the oldest. Both operations are O(1).
ts
class LRUCache<K, V> {
private entries = new Map<K, V>()
constructor(private readonly capacity: number) {
if (capacity < 1) throw new RangeError('capacity must be at least 1')
}
get(key: K): V | undefined {
if (!this.entries.has(key)) return undefined
const value = this.entries.get(key)!
this.entries.delete(key) // (1)
this.entries.set(key, value)
return value
}
set(key: K, value: V) {
if (this.entries.has(key)) {
this.entries.delete(key) // (2)
} else if (this.entries.size >= this.capacity) {
const oldest = this.entries.keys().next().value as K // (3)
this.entries.delete(oldest)
}
this.entries.set(key, value) // (4)
}
}
const productCache = new LRUCache<string, Product>(1000)- Delete and re-insert to move the key to the newest end of the map's order.
- Updating an existing key also counts as a use, so it moves to the newest end.
- The first key in a
Mapis the oldest, because maps keep insertion order.keys().next()reads it in O(1). - Insert at the newest end.
The classic follow-up: "without a Map's ordering". The textbook design is a hash map plus a doubly linked list. The map gives O(1) lookup of a node, and the list keeps nodes in order of use, so moving a node to the front and removing the tail are both O(1). Mention it even if you code the Map version.
103. Implement Function.prototype.bind.
The short answer
bind returns a new function that, when called, calls the original with a fixed this and with some arguments filled in first. So the polyfill captures the original function, the this value and the preset arguments, and returns a function that calls the original with apply, joining preset and new arguments. A complete version also handles being called with new, in which case the bound this is ignored.
js
Function.prototype.myBind = function (boundThis, ...preset) {
const original = this // (1)
if (typeof original !== 'function') {
throw new TypeError('myBind must be called on a function')
}
function bound(...args) {
if (new.target) { // (2)
return new original(...preset, ...args)
}
return original.apply(boundThis, [...preset, ...args]) // (3)
}
if (original.prototype) bound.prototype = Object.create(original.prototype) // (4)
return bound
}
function describe(greeting, punctuation) { return `${greeting}, ${this.name}${punctuation}` }
const forPriya = describe.myBind({ name: 'Priya' }, 'Hello')
forPriya('!') // 'Hello, Priya!'thisinsidemyBindis the function being bound, because it is called asdescribe.myBind(...)(question 15).new.targetis set when called withnew, and then the realbindignores the boundthisand constructs an instance instead.- Normal call: preset arguments first, then the new ones, with the fixed
this. - Keep
instanceofworking for instances made through the bound function.
Why interviewers like it: it tests this, closures, rest and spread, and apply in one small function.
104. Add a timeout to any promise.
The short answer
Race the promise against a second promise that rejects after the given time, using Promise.race, and clear the timer in finally so it does not keep running after the real promise wins. Note that this only stops waiting; the original operation keeps running in the background. To really cancel the work, pass an AbortSignal, such as AbortSignal.timeout(ms), to APIs that accept one, like fetch.
ts
class TimeoutError extends Error {}
function withTimeout<T>(work: Promise<T>, ms: number, label = 'operation'): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new TimeoutError(`${label} timed out after ${ms} ms`)), ms) // (1)
})
return Promise.race([work, timeout]).finally(() => clearTimeout(timer)) // (2)
}
const stock = await withTimeout(getStock('sku-9'), 2_000, 'stock lookup')
const res = await fetch('https://rates.example/api', { signal: AbortSignal.timeout(2_000) }) // (3)- A promise that only ever rejects, after
ms. - Whichever settles first wins.
finallyclears the timer either way, so a finished operation does not leave a pending timer that keeps a Node.js process alive. - Real cancellation:
fetchstops the request when the signal fires, instead of only ignoring the answer.
The point interviewers want you to make: Promise.race gives up waiting, but cannot stop the work. A slow database query that "timed out" this way is still running and still holding a connection. Pass an abort signal, or use the timeout settings of the database driver or HTTP client, so the work itself stops.