I came up with this simple experiment after reading the documentation on generators from MDN:
var nodes = {
type: \'root\',
value: [
{ type: \
You've found your solution, but just for the record here is another example a little different that print the types of all nodes in the tree (I added some deepness and vars)
var nodes = {
type: 'root',
value: [
{ type: 'char', value: 'a' },
{ type: 'char', value: 'b' },
{ type: 'char', value: [{type: 'int', value: 'c'}] },
],
};
var flattenTree = function* (root) {
yield root.type;
var subvalues = root.value;
for(var i in subvalues) {
var gen = flattenTree(subvalues[i]);
val = gen.next();
while(!val.done) {
if(val.value != undefined)
yield val.value;
val = gen.next();
}
}
}
var printTree = function() {
console.log("begin tree");
var generator = flattenTree(nodes);
var next = generator.next();
while(!next.done) {
console.log(next);
next = generator.next();
}
console.log("finish tree");
}
printTree();
Outputs:
~/workspace/tmp$ ../node/node --harmony test-gen.js
begin tree
{ value: 'root', done: false }
{ value: 'char', done: false }
{ value: 'char', done: false }
{ value: 'char', done: false }
{ value: 'int', done: false }
finish tree