Implement Array.prototype.flat
Implement Array.prototype.myFlat(depth = 1) so it behaves like the built-in flat, without calling flat or flatMap. The grader swaps both out while your code runs.
[1, [2], [3, [4]]].myFlat() // [1, 2, 3, [4]] [1, [2], [3, [4]]].myFlat(2) // [1, 2, 3, 4] [1, [2, [3, [4]]]].myFlat(Infinity) // [1, 2, 3, 4]
Rules
- Only real arrays are flattened (
Array.isArray). Strings, plain objects and array-likes are elements like any other. depthdefaults to 1 andInfinityis valid. A depth of 0 or less copies one level without flattening anything.- Holes (
[1, , 3]) are skipped at every level the method walks, the top level included, even at depth 0. A nested array past the depth is kept as it is, holes and all. - Return a new array and leave the input alone. Define the method with
function, not an arrow, sothisis the array. - Don't recurse. The last test nests 100,000 levels deep and flattens with
Infinity; a recursive walk overflows the call stack there, so that case only passes with an explicit stack.
Tests write a hole as the string "<hole>". The grader turns it into a real empty slot before calling you, and back into "<hole>" when it reads your result.
Hints
Hint 1
Walk with an index loop and use i in arr to skip holes. An element that is an array, with depth left, is walked with depth - 1; everything else is pushed.
Hint 2
To drop the recursion, keep a stack of [value, depth] pairs. Push children in reverse so popping yields them in order.
Hint 3
Infinity - 1 is still Infinity, so the same code handles "flatten everything".