Problem Statement
Implement a custom Array.prototype.myFlat(depth) method that works exactly like the native Array.prototype.flat().
The method should flatten a nested array up to the specified depth. If no depth is provided, default to 1. If depth is Infinity, flatten completely.
Constraint: Do NOT use the native .flat() method.
Constraints
- Array can contain any type (numbers, strings, nested arrays,
undefined,null) 0 <= depth <= Infinity- Array can be nested to arbitrary depth
- Must handle sparse arrays correctly
Example
[1, [2, [3, [4]]]].myFlat()
// [1, 2, [3, [4]]] (depth = 1)
[1, [2, [3, [4]]]].myFlat(2)
// [1, 2, 3, [4]]
[1, [2, [3, [4]]]].myFlat(Infinity)
// [1, 2, 3, 4]
[1, , [2, , 3]].myFlat()
// [1, 2, 3] (sparse slots removed)
Expected Implementation
Array.prototype.myFlat = function(depth = 1) {
// Your implementation here
};
Follow-ups
- What are the risks of modifying
Array.prototype? (prototype pollution) - How would you implement this iteratively instead of recursively (to avoid stack overflow on deeply nested arrays)?
- What's the time and space complexity of your solution?
- How does the native
Array.flat()handle non-array iterables inside the array?