Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Last active September 10, 2018 08:33
Show Gist options
  • Save mxriverlynn/9ff9dfe4e287f64805c5 to your computer and use it in GitHub Desktop.
Save mxriverlynn/9ff9dfe4e287f64805c5 to your computer and use it in GitHub Desktop.
recursing a tree structure with ES6 generators
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);
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" }
];
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);
}
}
}
var it = processData(data);
var res = it.next();
while(!res.done){
console.log(res.value);
res = it.next();
}
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
@granmoe
Copy link

granmoe commented Sep 8, 2016

This is a nice, concise example. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment