Resolve Promises Sequentially
Run promises one after another and collect the results in order — built with .then chaining, no async/await.
JavaScript · ES6 — Pratik Rai ·
The same result as the recursive flatten, with your own stack instead of the call stack.
Write flattenIterative(arr) returning every value from a deeply nested array in order.
The function must not call itself. This is the follow-up an interviewer asks once you have written the recursive version, and the point is the depth limit: recursion runs out of stack, an explicit stack runs out of memory.
Input:
JSfile.javascript1flattenIterative([1, [2, [3, [4]]], 5]);
Output:
[1, 2, 3, 4, 5]
Order is preserved, however deep the nesting goes.
The recursive flatten is three lines and correct. The follow-up asks for it without recursion, and the reason is depth: recursion is bounded by the engine's call stack, which gives out somewhere around ten thousand frames and throws RangeError.
Do the same job with a stack you own.
JSfile.javascript1function flattenIterative(arr) { 2 const out = []; 3 const stack = arr.slice(); 4 while (stack.length > 0) { 5 const item = stack.pop(); 6 if (Array.isArray(item)) { 7 for (let i = 0; i < item.length; i += 1) stack.push(item[i]); 8 } else { 9 out.push(item); 10 } 11 } 12 return out.reverse(); 13}
Popping from the end visits items in reverse, so the result comes out backwards and needs reversing. Pushing children in reverse and popping from the front is the alternative; say which you chose and why.
The suite includes a twenty-thousand-deep array specifically because a recursive implementation throws on it. The tradeoff is honest rather than free: the recursion limit becomes a memory limit, which is much larger but not infinite.
Goal: Flatten completely using an explicit stack, with no recursive call.
RangeError. Your own stack lives in the heap, so the depth limit becomes memory instead.flat(Infinity) handles very deep arrays that a hand-written recursion would not.Continue learning with these related challenges
Run promises one after another and collect the results in order — built with .then chaining, no async/await.
JavaScript · ES6 — Pratik Rai ·
Group an array into buckets by a key function — now a real language feature as Object.groupBy.
JavaScript · ES6 — Pratik Rai ·
Turn a flat array of nodes with parentId into a nested tree — the shape behind every file explorer and nested menu.
JavaScript · ES6 — Pratik Rai ·
Run promises one after another and collect the results in order — built with .then chaining, no async/await.
JavaScript · ES6
Pratik Rai ·
Group an array into buckets by a key function — now a real language feature as Object.groupBy.
JavaScript · ES6
Pratik Rai ·
Turn a flat array of nodes with parentId into a nested tree — the shape behind every file explorer and nested menu.
JavaScript · ES6
Pratik Rai ·