Full answer
- flatten(array, depth): for each item, if it is an array and depth remains, flatten it with depth - 1, else push it. Array.prototype.flat does the same, so the exercise is about recursion and the depth rule (Infinity means all levels). Very deep arrays can exceed the call stack with recursion, which an explicit stack avoids.
- chunk(array, size): loop with index += size and slice. Reject size less than 1 (an infinite loop otherwise). The last chunk can be shorter. An empty array gives [].
- groupBy(array, keyFn): use a loop and an object or Map, pushing each item to its group. Use Object.create(null) or a Map when keys can be user input, to avoid keys such as proto causing trouble. Node 21 and later also has Object.groupBy and Map.groupBy.
- uniqueBy(array, keyFn): a Set of seen keys, keep the first item per key and keep the order. For primitives, [...new Set(array)] is enough.
- memoize(fn, keyFn): a Map from key to result. The default key must be chosen carefully (JSON.stringify of arguments is simple but slow and wrong for functions and cycles). Cache promises, not only values, for async functions, so that concurrent calls share work. Limit the size (LRU) or the cache grows without bound, which is a memory leak for functions with many different inputs.
Interview habits: ask about edge cases first, state the time and space complexity (all of these are O(n) except flatten with deep nesting), and write a few small tests.
const flatten = (array, depth = Infinity) =>
array.reduce((out, item) => (Array.isArray(item) && depth > 0 ? out.concat(flatten(item, depth - 1)) : (out.push(item), out)), []);
function chunk(array, size) {
if (!Number.isInteger(size) || size < 1) throw new RangeError('size must be a positive integer');
const out = [];
for (let i = 0; i < array.length; i += size) out.push(array.slice(i, i + size));
return out;
}
function groupBy(array, keyFn) {
const groups = Object.create(null);
for (const item of array) (groups[keyFn(item)] ??= []).push(item);
return groups;
}
function uniqueBy(array, keyFn) {
const seen = new Set();
return array.filter((item) => { const key = keyFn(item); if (seen.has(key)) return false; seen.add(key); return true; });
}
function memoize(fn, keyFn = (...args) => JSON.stringify(args)) {
const cache = new Map();
const memoized = (...args) => {
const key = keyFn(...args);
if (cache.has(key)) return cache.get(key);
const result = fn(...args);
cache.set(key, result); // for async functions this stores the promise, so concurrent calls share it
return result;
};
memoized.cache = cache;
return memoized;
}
console.log('flatten all :', JSON.stringify(flatten([1, [2, [3, [4, []]]], 5])));
console.log('flatten depth1:', JSON.stringify(flatten([1, [2, [3, [4]]]], 1)), '| same as flat(1):', JSON.stringify([1, [2, [3, [4]]]].flat(1)) === JSON.stringify(flatten([1, [2, [3, [4]]]], 1)));
console.log('chunk :', JSON.stringify(chunk([1, 2, 3, 4, 5], 2)), JSON.stringify(chunk([], 3)));
console.log('chunk size 0 :', (() => { try { chunk([1], 0); } catch (e) { return e.name; } })());
const people = [{ name: 'Asha', city: 'Pune' }, { name: 'Ravi', city: 'Delhi' }, { name: 'Meera', city: 'Pune' }, { name: 'Asha', city: 'Goa' }];
console.log('groupBy city :', JSON.stringify(groupBy(people, (p) => p.city)));
console.log('groupBy __proto__ safe:', JSON.stringify(groupBy([{ k: '__proto__' }], (x) => x.k)), '| Object.groupBy equal:', JSON.stringify(groupBy(people, (p) => p.city)) === JSON.stringify(Object.groupBy(people, (p) => p.city)));
console.log('uniqueBy name :', uniqueBy(people, (p) => p.name).map((p) => p.city).join(', '));
let calls = 0;
const square = memoize((n) => { calls++; return n * n; });
square(4); square(4); square(5);
console.log('memoize : calls =', calls, '| cache size =', square.cache.size);The utilities are checked with small inputs and, where a built-in exists (flat, Object.groupBy), against the built-in result. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): flatten all : [1,2,3,4,5] flatten depth1: [1,2,[3,[4]]] | same as flat(1): true chunk : [[1,2],[3,4],[5]] [] chunk size 0 : RangeError groupBy city : {"Pune":[{"name":"Asha","city":"Pune"},{"name":"Meera","city":"Pune"}],"Delhi":[{"name":"Ravi","city":"Delhi"}],"Goa":[{"name":"Asha","city":"Goa"}]} groupBy __proto__ safe: {"__proto__":[{"k":"__proto__"}]} | Object.groupBy equal: true uniqueBy name : Pune, Delhi, Pune memoize : calls = 2 | cache size = 2
Key points
- flatten needs a depth rule and a recursion or stack choice.
- chunk must reject sizes below one.
- groupBy should be safe against odd keys such as __proto__.
- uniqueBy keeps the first item and the order.
- memoize needs a good key and a size limit.
Common mistakes
- Using a plain object for groups, so '__proto__' or 'constructor' keys misbehave.
- An infinite loop in chunk when size is 0.
- Memoizing with a key that collides (for example arguments joined with a comma).
- A cache with no size limit.
- Mutating the input array.
Follow-ups
- How would you add an LRU limit to memoize?
- What is the complexity of each function?
- How does Map.groupBy differ from Object.groupBy?
Tips
- Ask about edge cases first.
- State complexity.
- Say when the built-in exists.