Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
749 B
1
Indexable
Never
var flat2 = 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;
};