Skip to content

Instantly share code, notes, and snippets.

@fitzgen
Created August 30, 2013 20:07
Show Gist options
  • Save fitzgen/6393792 to your computer and use it in GitHub Desktop.
Save fitzgen/6393792 to your computer and use it in GitHub Desktop.
http://swannodette.github.io/2013/08/24/es6-generators-and-csp/ ported to SpiderMonkey (at least until ES6 generators are fully supported, which should be within the next month or so)
function go_(machine, step) {
while(!step.done) {
try {
var arr = step(),
state = arr[0],
value = arr[1];
switch (state) {
case "park":
setImmediate(function() { go_(machine, step); });
return;
case "continue":
step = machine.next(value);
break;
}
} catch(e) {
// todo: only catch stop iteration
return;
}
}
}
function go(machine) {
var gen = machine();
go_(gen, gen.next());
}
function put(chan, val) {
return function() {
if(chan.length == 0) {
chan.unshift(val);
return ["continue", null];
} else {
return ["park", null];
}
};
}
function take(chan) {
return function() {
if(chan.length == 0) {
return ["park", null];
} else {
var val = chan.pop();
return ["continue", val];
}
};
}
/////////////////////////////////////////////
var c = [];
go(function () {
for(var i = 0; i < 10; i++) {
yield put(c, i);
console.log("process one put", i);
}
yield put(c, null);
});
go(function () {
while(true) {
var val = yield take(c);
if(val == null) {
break;
} else {
console.log("process two took", val);
}
}
});
// todo: use postMessage
window.setImmediate = cb => setTimeout(cb, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment