/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
const arrStack = [{arr, i: 0}];
const res = [];
while(arrStack.length) {
let curr = arrStack[arrStack.length-1];
let fromI = curr.i;
let currArr = curr.arr;
let shouldPop = true;
for (let i = fromI; i < currArr.length; i++) {
let item = currArr[i];
if (item.length !== undefined) {
if(arrStack.length <= n) {
arrStack.push({arr: item, i: 0});
curr.i = i+1;
shouldPop = false;
break;
}
}
res.push(item);
}
if(shouldPop) {
arrStack.pop();
}
}
return res;
};