Nested Array Generator
Write a generator function inorderTraversal(arr) that yields every integer in a multidimensional array, in order.
Because it is a generator, the caller can take values one at a time and stop early — nothing is materialised up front.
Examples
[...inorderTraversal([1, [2, 3], [[4]]])];[1, 2, 3, 4]Constraints
- 0 <= number of integers <= 10^5
- Nesting may be arbitrarily deep
Notes
- `yield*` delegates to a recursive call and forwards every value from it.
- Calling a generator function runs none of its body — the first `next()` does.
Hints
Nested Array Generator (reference solution)
One way to do it. The Editorial tab walks through why it is written this way.
Solution
1function* inorderTraversal(arr) {
2 for (const item of arr) {
3 if (Array.isArray(item)) yield* inorderTraversal(item);
4 else yield item;
5 }
6}Editorial: Nested Array Generator
Yielding instead of returning
A function that returns an array has to build the whole array first. A generator hands back one value at a time, so a caller who wanted the first three can stop after three.
Approach
yield* delegates to a recursive call and forwards every value it produces.
Implementation
function* inorderTraversal(arr) { for (const item of arr) { if (Array.isArray(item)) yield* inorderTraversal(item); else yield item; } }
Worth knowing
Calling a generator function runs none of its body — it returns an iterator, and the first next() starts execution. That laziness is the entire reason to reach for one.
yield* is doing real work here: without it you would loop over the inner generator and yield each value manually. With it, the delegation is one line and the recursion reads like the non-generator version.