Created
May 13, 2020 15:12
-
-
Save hax/9cf04a4e090c5bab1d658b72c996f82b to your computer and use it in GitHub Desktop.
A experimental Channel in JS
This file contains hidden or 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
// kotlin channel: https://kotlinlang.org/docs/reference/coroutines/channels.html | |
// golang channel | |
class Channel { | |
constructor() { | |
this._s = null | |
this._r = null | |
} | |
send(v) { | |
if (this._r) { | |
this._r(v) | |
this._r = null | |
return | |
} else { | |
if (this._s) throw new Error() | |
return new Promise(r => this._s = [r, v] ) | |
} | |
} | |
receive() { | |
if (this._s) { | |
const [r, v] = this._s | |
this._s = null | |
r() | |
return v | |
} else { | |
if (this._r) throw new Error() | |
return new Promise(r => this._r = r) | |
} | |
} | |
async *[Symbol.asyncIterator]() { | |
for (;;) yield this.receive() | |
} | |
} | |
const ch = new Channel() | |
void async function() { | |
for await (const x of ch) console.log(x) | |
}() | |
setInterval(() => { | |
ch.send((Math.random() * 100) | 0) | |
}, 100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment