Interview Questions 3
Flatten and memoize.
Some interviews ask you to write a utility by hand, even though a built in one exists. It shows you understand recursion and functions. Let's write flatten and memoize.

- Write a utility by hand
- Recursion and functions
- flatten and memoize
Flatten
Flatten turns nested arrays into one flat array. For each item, if it's an array, we flatten it recursively, and spread the result in. Otherwise we just add it. The built in flat, with infinity, gives the same answer. Run it.
function flatten(arr) {
const out = [];
for (const item of arr) {
if (Array.isArray(item)) out.push(...flatten(item));
else out.push(item);
}
return out;
}
const nested = [1, [2, [3, [4]], 5], [[6]]];
console.log(flatten(nested));
console.log(nested.flat(Infinity));[ 1, 2, 3, 4, 5, 6 ] [ 1, 2, 3, 4, 5, 6 ]
Memoize
Memoize wraps a slow function, and remembers its answers in a map. If we've seen the argument before, we return the saved answer instantly. Here, slow square counts how often it really runs. We call it four times, but it only does the work twice. Run it.
function memoize(fn) {
const cache = new Map();
return (x) => {
if (!cache.has(x)) cache.set(x, fn(x));
return cache.get(x);
};
}
let calls = 0;
const slowSquare = (n) => { calls++; return n * n; };
const fastSquare = memoize(slowSquare);
console.log(fastSquare(9), fastSquare(9), fastSquare(4), fastSquare(4));
console.log("Real calls:", calls);81 81 16 16 Real calls: 2
Summary
Flatten uses recursion, and memoize uses a closure with a map. Both show you understand functions deeply. Next, one more round, on async questions.
Key takeaways- Recursion for nesting
- Cache in a Map
- Closures everywhere