-
-
Save mxriverlynn/9ff9dfe4e287f64805c5 to your computer and use it in GitHub Desktop.
recursing a tree structure with ES6 generators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function *doStuff(){ | |
yield 1; | |
yield 2; | |
yield *doStuff(); | |
} | |
var it = doStuff(); | |
var res; | |
res = it.next(); | |
console.log(res.value); | |
res = it.next(); | |
console.log(res.value); | |
res = it.next(); | |
console.log(res.value); | |
res = it.next(); | |
console.log(res.value); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var data = [ | |
{ id: "0" }, | |
{ | |
id: "1", | |
children: [ | |
{ | |
id: "1.1", | |
children: [ | |
{ | |
id: "1.1.1", | |
children: [ | |
{ | |
id: "1.1.1.1", | |
children: [ | |
{ id: "1.1.1.1.1" }, | |
{ id: "1.1.1.1.2" }, | |
{ id: "1.1.1.1.3" } | |
] | |
}, | |
{ id: "1.1.1.2" }, | |
{ id: "1.1.1.3" } | |
] | |
}, | |
{ id: "1.1.2" }, | |
{ id: "1.1.3" }, | |
] | |
}, | |
{ id: "1.2" }, | |
{ id: "1.3" } | |
] | |
}, | |
{ id: "2" }, | |
{ id: "3" } | |
]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function *processData(data){ | |
if (!data) { return; } | |
for (var i = 0; i< data.length; i++){ | |
var val = data[i]; | |
yield val.id; | |
if (val.children) { | |
yield *processData(val.children); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var it = processData(data); | |
var res = it.next(); | |
while(!res.done){ | |
console.log(res.value); | |
res = it.next(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
0 | |
1 | |
1.1 | |
1.1.1 | |
1.1.1.1 | |
1.1.1.1.1 | |
1.1.1.1.2 | |
1.1.1.1.3 | |
1.1.1.2 | |
1.1.1.3 | |
1.1.2 | |
1.1.3 | |
1.2 | |
1.3 | |
2 | |
3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a nice, concise example. Thanks!