2625. Flatten Deeply Nested Array
https://leetcode.com/problems/flatten-deeply-nested-array/
Javascript
var flat = function (arr, n) {
function* liter(item, level) {
if (!Array.isArray(item)) {
yield item
} else if (level < 0) {
yield item
} else {
for (const child of item) {
for (const subItem of liter(child, level-1)) {
yield subItem
}
}
}
}
return Array.from(liter(arr, n))
};
Typescript
type MultiDimensionalArray = (number | MultiDimensionalArray)[];
var flat = function (arr: MultiDimensionalArray, n: number): MultiDimensionalArray {
function* liter(item, level) {
if (!Array.isArray(item)) {
yield item
} else if (level < 0) {
yield item
} else {
for (const child of item) {
for (const subItem of liter(child, level-1)) {
yield subItem
}
}
}
}
return Array.from(liter(arr, n))
};