Skip to content

Instantly share code, notes, and snippets.

@tlkahn
Forked from mxriverlynn/0.js
Created December 6, 2015 18:14
Show Gist options
  • Save tlkahn/440fadfd54f0c4d02288 to your computer and use it in GitHub Desktop.
Save tlkahn/440fadfd54f0c4d02288 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment