Skip to content

Instantly share code, notes, and snippets.

@b-studios
Created October 26, 2017 07:06
Show Gist options
  • Save b-studios/8e6d6e3026dc25994dc93c915a2514f7 to your computer and use it in GitHub Desktop.
Save b-studios/8e6d6e3026dc25994dc93c915a2514f7 to your computer and use it in GitHub Desktop.
Quick experiments with yielding effects in javascript
function * get() { return yield { label: "get", payload: null }; }
function * put(s) { return yield { label: "put", payload: s }; }
function * state(init, prog) {
var s = init;
var cmd = prog.next();
while (!cmd.done) {
switch (cmd.value.label) {
case "get":
cmd = prog.next(s);
break;
case "put":
console.log(cmd);
s = cmd.value.payload;
cmd = prog.next(null)
break;
default:
cmd = prog.next(yield cmd.value);
}
}
return cmd.value;
}
function * read() { return yield { label: "read", payload: null }; }
function * reader(init, prog) {
var s = init;
var cmd = prog.next();
while (!cmd.done) {
switch (cmd.value.label) {
case "read":
cmd = prog.next(s);
s = s + 1;
break;
default:
cmd = prog.next(yield cmd.value);
}
}
return cmd.value;
}
function * example() {
var x = yield * get();
yield * put(4);
var z1 = yield * read();
var y = yield * get();
var z2 = yield * read();
console.log(x, z1, z2, y)
}
// run the example
var p = state(1, reader(2, example()))
p.next();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment