problems(js): add “2649. Nested Array Generator”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
28e633e89a
commit
4c3c626f07
1 changed files with 37 additions and 0 deletions
37
problems/js/nested-array-generator.js
Normal file
37
problems/js/nested-array-generator.js
Normal file
|
@ -0,0 +1,37 @@
|
||||||
|
/**
|
||||||
|
* @param {Array} arr
|
||||||
|
* @return {Generator}
|
||||||
|
*/
|
||||||
|
var inorderTraversal = function*(arr) {
|
||||||
|
let stack = [[arr, 0]];
|
||||||
|
|
||||||
|
while (stack.length) {
|
||||||
|
let [arr, i] = stack.pop();
|
||||||
|
if (i >= arr.length) {
|
||||||
|
// finished with the nested array
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// if it's a nested array
|
||||||
|
if (arr[i] instanceof Array) {
|
||||||
|
// gotta continue with the next element of the array
|
||||||
|
stack.push([arr, i + 1]);
|
||||||
|
|
||||||
|
// gotta start with the first element of the nested
|
||||||
|
stack.push([arr[i], 0]);
|
||||||
|
|
||||||
|
// yielding is done only on the elements themselves
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
yield arr[i];
|
||||||
|
stack.push([arr, i + 1]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* const gen = inorderTraversal([1, [2, 3]]);
|
||||||
|
* gen.next().value; // 1
|
||||||
|
* gen.next().value; // 2
|
||||||
|
* gen.next().value; // 3
|
||||||
|
*/
|
Loading…
Reference in a new issue