How do you implement polyfills for Array.prototype.flat and flatMap supporting custom and infinite recursion depth?
In Simple Words:
Array.prototype.flat recursively concatenates sub-array elements up to a specified depth (defaulting to 1, or Infinity for complete flattening), which can be implemented either recursively with array reduction or iteratively using a stack to prevent call stack overflow on deeply nested arrays.
1. Recursive Implementation with Depth Control
function flatArrayRecursive(arr, depth = 1) {
if (!Array.isArray(arr) || depth <= 0) {
return Array.isArray(arr) ? [...arr] : [];
}
return arr.reduce((acc, item) => {
if (Array.isArray(item) && depth > 0) {
acc.push(...flatArrayRecursive(item, depth - 1));
} else {
acc.push(item);
}
return acc;
}, []);
}
2. Iterative Stack-Based Implementation (Prevents Call Stack Overflow)
When dealing with arrays nested thousands of levels deep, recursion throws RangeError: Maximum call stack size exceeded. An iterative stack processes arbitrary depths safely in $O(N)$ space and time.
function flatArrayIterative(arr, depth = 1) {
if (!Array.isArray(arr)) return [];
if (depth <= 0) return [...arr];
// Store elements paired with their remaining flattening depth
const stack = arr.map((item) => ({ item, depth }));
const result = [];
while (stack.length > 0) {
const { item, depth: d } = stack.pop();
if (Array.isArray(item) && d > 0) {
// Push in reverse to maintain left-to-right order on pop
for (let i = item.length - 1; i >= 0; i--) {
stack.push({ item: item[i], depth: d - 1 });
}
} else {
result.push(item);
}
}
return result;
}
3. Polyfill for Array.prototype.flatMap
Maps each element using a mapping function and flattens the result by depth 1.
function flatMapPolyfill(arr, callback, thisArg) {
return arr.map(callback, thisArg).reduce((acc, val) => {
if (Array.isArray(val)) {
acc.push(...val);
} else {
acc.push(val);
}
return acc;
}, []);
}
// Verification:
const nested = [1, [2, [3, [4, 5]]]];
console.log(flatArrayRecursive(nested, 1)); // [1, 2, [3, [4, 5]]]
console.log(flatArrayRecursive(nested, 2)); // [1, 2, 3, [4, 5]]
console.log(flatArrayIterative(nested, Infinity)); // [1, 2, 3, 4, 5]
const phrases = ["hello world", "goodbye all"];
console.log(flatMapPolyfill(phrases, s => s.split(" ")));
// ["hello", "world", "goodbye", "all"]