Nested arrays turn up everywhere: pages of results, each a list; a menu tree's items; rows of cells. flat opens nested arrays into one list, as many levels deep as you ask. It is also the classic recursion exercise, with a few spec details that a quick version gets wrong: what counts as an array, what happens to holes, and what depth really means.
Write Array.prototype.myFlat(depth) in flat.js. It must behave like the built-in Array.prototype.flat for every case below.
With no depth, myFlat opens one level: arrays inside arrays stay as they are.
With a depth, it opens that many levels; Infinity opens all of them, even 1,000 levels deep.
depth is converted to a whole number: "2" is 2, 1.9 is 1, NaN and null are 0. A negative depth counts as 0. Only undefined means the default 1. A depth that is a BigInt or a Symbol, or an object whose valueOf returns one, throws a TypeError, as the built-in does ([[1]].flat(1n) throws).
With depth 0, the result is a copy with nothing opened, but still without holes.
Holes are removed from this and from every array that is opened; holes inside an array that is not opened stay. Empty arrays that are opened add nothing. undefined and null items are kept.
Only real arrays are opened (as Array.isArray says). Array-like objects, strings and Sets are added as they are, and Symbol.isConcatSpreadable makes no difference.
The order of the items is kept, and objects are the same objects, not copies.
myFlat works on an array-like this, called with Array.prototype.myFlat.call(…), and reads its length once. length is converted to a whole number from 0 up ("2" and 2.9 are 2, -1 is 0); a BigInt or Symbol length throws a TypeError.
It throws a TypeError when called on null or undefined.
Plain JavaScript in a browser page; the tests call Array.prototype.myFlat from flat.js.
flat.js starts with "use strict". Keep it: in strict mode, this inside myFlat is exactly the value it was called on, so a call on null can be detected.
Not allowed: the built-in flat and flatMap. The tests delete them from Array.prototype while myFlat runs.
Out of scope: subclasses of Array (myFlat always returns a plain array), and arrays nested so deeply that recursion runs out of stack.