Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Polyfills: map, filter, reduce, Promise.all — JavaScript interview guide

22 / 23Interview CodingHigh priorityHard 40 min

Polyfills: map, filter, reduce, Promise.all

Writing built-in methods from scratch proves you understand them. These four come up most often.

See it run

Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.

Promise.all from scratch: results stay in order

Execution phaseStep 1/9
script.js
1function promiseAll(items) {
2 return new Promise((resolve, reject) => {
3 const results = [];
4 let done = 0;
5 items.forEach((p, i) => {
6 p.then((value) => {
7 results[i] = value;
8 if (++done === items.length) resolve(results);
9 }, reject);
10 });
11 });
12}
13
▶const slow = wait(300, "A");
15const fast = wait(100, "B");
16promiseAll([slow, fast]).then(console.log);
Call Stack
last in, first out
Globalrunning
Memory / Scope

empty

Web APIs (browser)
runs outside JS
timer 300ms → "A"
timer 100ms → "B"
Event Loop

Waits until the Call Stack is empty. Microtasks always go first.

Microtask Queue
promises · high priority

empty

Callback Queue
setTimeout, events

empty

Console

nothing printed yet

What happens:Two promises: slow resolves with "A" after 300ms, fast with "B" after 100ms. Both timers start right away.

Tip: click the box and use ← → keys to step, space to play.

Explained simply

Array methods

Use this to access the array; skip holes with "in".

Array.prototype.myMap = function (cb, thisArg) {
  const out = [];
  for (let i = 0; i < this.length; i++) {
    if (i in this) out[i] = cb.call(thisArg, this[i], i, this);
  }
  return out;
};

Array.prototype.myReduce = function (cb, init) {
  let i = 0;
  let acc = init;
  if (arguments.length < 2) {
    if (this.length === 0) throw new TypeError("Reduce of empty array with no initial value");
    acc = this[0];
    i = 1;
  }
  for (; i < this.length; i++) acc = cb(acc, this[i], i, this);
  return acc;
};

Promise.all

Keep results in order and reject on the first error.

function promiseAll(items) {
  return new Promise((resolve, reject) => {
    const results = [];
    let done = 0;
    if (items.length === 0) return resolve([]);
    items.forEach((item, i) => {
      Promise.resolve(item).then((value) => {
        results[i] = value;
        if (++done === items.length) resolve(results);
      }, reject);
    });
  });
}

Remember this

  • Pass index and array to callbacks like the real methods.
  • Promise.resolve(item) handles non-promise values.
  • Keep result order by index, not by finish time.

Interview questions

Why use Promise.resolve(item) inside promiseAll?

So plain values and thenables work too, exactly like the real Promise.all.

Practice

  1. Write myFilter, myFlat(depth) and Promise.allSettled.

Keep learning