Skip to content

Interview PrepWrite it yourself · Core

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.

callsdebounce300 ms of quietrunsthrottlerunrunrunrun0300600900 ms
Wait for quiet, or run on a beat. Debounce runs once, after the calls stop. Throttle runs at most once per window, at a steady rate, while calls keep coming.
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))
  1. The timer lives in a closure, shared by every call to debounced (question 11).
  2. Each call cancels the pending run. clearTimeout(undefined) is harmless, so no check is needed.
  3. Start a fresh wait.
  4. Run with the latest arguments once nobody has called for waitMs.
  5. A cancel method, 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 leading option that calls fn when timer is undefined.
  • this: the arrow function above ignores this. To support methods, write function (this: unknown, ...args) and call fn.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))
  1. When the function last ran. Starting at 0 means the very first call runs immediately.
  2. How long until the window is over.
  3. Window over: run now, and cancel any scheduled trailing run, because this one replaces it.
  4. Inside the window: remember the latest arguments.
  5. 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:

DebounceThrottle
RunsOnce, after calls stopRegularly, at most once per window
During a long burstNever, until it endsEvery window
Good forSearch box, autosave, resize endScroll, 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
  1. The key builder. JSON.stringify works for simple arguments. Allow a custom one for objects, where only an id might matter.
  2. has, not a truthiness check, so cached results like 0, '' or null are still returned from the cache.
  3. 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
  1. Enough arguments collected: call the original function.
  2. 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
  1. Primitives and functions are returned as they are. Functions are shared, not copied.
  2. Already copied? Return that copy. This is what breaks cycles.
  3. Dates need a new Date, or the clone would be an empty object.
  4. A new container of the same kind, keeping the prototype so class instances stay instances.
  5. Register the copy before recursing, so a cycle that leads back here finds it.
  6. Reflect.ownKeys includes symbol keys, which Object.keys would 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]]]
  1. Take the last item from the stack.
  2. An array goes back on the stack as its items.
  3. 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]
  1. Accept any iterable, as the real one does, by copying it into an array.
  2. Empty input resolves immediately, otherwise the promise would never settle.
  3. Promise.resolve wraps plain values, so 42 works like an already-fulfilled promise.
  4. Store by index, not with push, so a fast third promise does not land in position one.
  5. Resolve only when every input has finished.
  6. The first rejection rejects the whole thing. Later calls to reject or resolve are 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".

worker 1task 1task 4worker 2task 2, slowtask 7worker 3task 3task 5task 6time → never more than 3 at once; a free worker takes the next task
Three lanes, one queue. Each worker loops: take the next task, finish it, take another. A slow task only holds up its own lane.
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))
  1. A shared position in the list.
  2. 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.
  3. Process it, and store the result at its own index, so the order matches the input.
  4. Start limit workers, or fewer if there are fewer items.
  5. 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 a failed flag in the loop, or pass an AbortSignal. To collect all outcomes instead, catch inside worker and 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-limit do 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 })
  1. Try the call. return await is needed so a rejection is caught here (question 54).
  2. Give up when attempts run out, or when the error is not worth retrying.
  3. Exponential growth: 200, 400, 800, 1,600 ms, capped at 5 seconds.
  4. 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:

RetryDo not retry
Timeouts, connection resets400 Bad Request, validation errors
429 Too Many Requests, respecting Retry-After401 or 403
502, 503, 504404 for a resource that does not exist
Idempotent operations, or ones sent with an idempotency keyA 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()
  1. Return an unsubscribe function, a convenient pattern used by many libraries.
  2. once removes itself first, so even if the listener throws, it never runs again.
  3. 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).

startABC① get(A)BCAA moved to the newest end② set(D)BCADfull: oldest, B, is removedoldestnewest
Use it, and it moves to the front of the line. ① A read moves an entry to the newest end. ② When the cache is full, the entry at the oldest end leaves to make room.
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)
  1. Delete and re-insert to move the key to the newest end of the map's order.
  2. Updating an existing key also counts as a use, so it moves to the newest end.
  3. The first key in a Map is the oldest, because maps keep insertion order. keys().next() reads it in O(1).
  4. 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!'
  1. this inside myBind is the function being bound, because it is called as describe.myBind(...) (question 15).
  2. new.target is set when called with new, and then the real bind ignores the bound this and constructs an instance instead.
  3. Normal call: preset arguments first, then the new ones, with the fixed this.
  4. Keep instanceof working 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)
  1. A promise that only ever rejects, after ms.
  2. Whichever settles first wins. finally clears the timer either way, so a finished operation does not leave a pending timer that keeps a Node.js process alive.
  3. Real cancellation: fetch stops 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.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
JavaScript & TypeScript
Basics
Async
TypeScript
Write it yourself
Other topics
Nothing picked yet