This problem was asked by Meta
What is a polyfill ?
In web development, a polyfill is code that implements a feature on web browsers that do not natively support the feature
Please implement your own Array.prototype.flat()
Example
const arr = [1, [2], [3, [4]]];
flat(arr) // [1, 2, 3, [4]]
flat(arr, 1) // [1, 2, 3, [4]]
flat(arr, 2) // [1, 2, 3, 4]
Follow up: Are you able to solve it both recursively and iteratively?
Solution
Recursion implementation
if (!Array.prototype.flat) {
Array.prototype.flat = function (depth = Infinity) {
const result = [];
function flatten(arr, currentdepth) {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i]) && currentdepth < depth) {
flatten(arr[i], currentdepth + 1);
} else {
result.push(arr[i]);
}
}
}
flatten(this, 0);
return result;
};
}
Iterative implementation
if (!Array.prototype.customFlat) {
Array.prototype.customFlat = function (depth = Infinity) {
const arr = [...this];
const result = [];
while (arr.length) {
const current = arr.shift();
if (Array.isArray(current) && depth > 0) {
--depth;
arr.unshift(...current);
} else {
result.push(current);
}
}
return result;
};
}
Top comments (0)