Skip to content

Instantly share code, notes, and snippets.

@jdowner
Last active August 29, 2015 14:05
Show Gist options
  • Save jdowner/48f8f96964abf3e48fa7 to your computer and use it in GitHub Desktop.
Save jdowner/48f8f96964abf3e48fa7 to your computer and use it in GitHub Desktop.
Javascript coroutine experiment
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>coroutine-traversal-example</title>
</head>
<script src="traversal.js"></script>
<body>
</body>
<script>
function init() {
var a = new co.node('a');
var b = new co.node('b');
var c = new co.node('c');
var d = new co.node('d');
var e = new co.node('e');
var f = new co.node('f');
a.children.push(b);
a.children.push(c);
a.children.push(f);
c.children.push(d);
c.children.push(e);
var iter = new co.traversal(a);
for(var current = iter.next(); current != null; current = iter.next()){
console.log(current.name);
}
}
window.addEventListener('load', init, false)
</script>
</html>
var co = {
node: function(name){
this.children = [];
this.name = name;
},
traversal: function(root){
var iterator = function*(){
var stack = [root];
while(stack.length > 0){
var node = stack.pop();
for(var i = 0; i < node.children.length; i++){
stack.push(node.children[node.children.length - 1 - i]);
}
yield node;
}
while(true){
yield null;
}
}();
this.next = function(){
return iterator.next().value;
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment