Created
October 26, 2017 07:06
-
-
Save b-studios/8e6d6e3026dc25994dc93c915a2514f7 to your computer and use it in GitHub Desktop.
Quick experiments with yielding effects in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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