Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Created September 17, 2019 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/840a20a24370ad71b3639cc756e6cb10 to your computer and use it in GitHub Desktop.
Save dfkaye/840a20a24370ad71b3639cc756e6cb10 to your computer and use it in GitHub Desktop.
// 17 Sept 2019
// from david nolan's 24 aug 2013 post - http://swannodette.github.io/2013/08/24/es6-generators-and-csp
function go_(it, step) {
console.log({ it, step });
while(!step.done) {
var arr = step.value(),
state = arr[0],
value = arr[1];
switch (state) {
case "park":
// setImmediate(function() { go_(machine, step); });
setTimeout(function() { go_(it, step); }, 1);
return;
case "continue":
step = it.next(value);
break;
}
}
}
// function go(machine) {
// var gen = machine();
// go_(gen, gen.next());
// }
function go(generator) {
var it = generator();
go_(it, it.next());
}
function put(chan, val) {
return function() {
if(chan.length == 0) {
chan.unshift(val);
return ["continue", null];
}
// else {
// return ["park", null];
//}
return ["park", null];
};
}
function take(chan) {
return function() {
if(chan.length == 0) {
return ["park", null];
}
//else {
// var val = chan.pop();
// return ["continue", val];
//}
return ["continue", chan.pop()];
};
}
/* test it out */
var c = ['a'];
go(function* () {
for (var i = 0; i < 10; i++) {
yield put(c, i);
console.log("process one put", i);
}
yield put(c, void 0);
});
go(function* () {
while(true) {
var val = yield take(c);
if(val == null) {
break;
}
//else {
console.log("process two took", val);
//}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment