Created
September 8, 2018 17:23
-
-
Save thanhpk/38b57f3ce51b7086f7dfe724cde7f349 to your computer and use it in GitHub Desktop.
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
class Channel { | |
constructor () { | |
this.csm = [] | |
this.msg = [] | |
} | |
enqueue (data) { | |
this.msg.push(data) | |
this.pass() | |
} | |
dequeue () { | |
return new Promise(resolve => { | |
let p = { resolve } | |
this.csm.push(p) | |
this.pass() | |
setTimeout(() => { | |
p.resolve = undefined | |
resolve([undefined, 'timeout']) | |
}, 500) | |
}) | |
} | |
pass () { | |
if (this.csm.length == 0 || this.msg.length == 0) return | |
var cons = this.csm.shift() | |
/* ignore outdated consumer */ | |
if (!cons.resolve) { | |
this.pass() | |
return | |
} | |
var mess = this.msg.shift() | |
cons([mess, undefined]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment