Skip to content

Instantly share code, notes, and snippets.

@thanhpk
Created September 8, 2018 17:23
Show Gist options
  • Save thanhpk/38b57f3ce51b7086f7dfe724cde7f349 to your computer and use it in GitHub Desktop.
Save thanhpk/38b57f3ce51b7086f7dfe724cde7f349 to your computer and use it in GitHub Desktop.

Revisions

  1. thanhpk created this gist Sep 8, 2018.
    37 changes: 37 additions & 0 deletions array.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    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])
    }
    }