Skip to content

Instantly share code, notes, and snippets.

@ziap
Created March 30, 2024 13:54
Show Gist options
  • Save ziap/c6ec49b0dd652814457616f7785fae54 to your computer and use it in GitHub Desktop.
Save ziap/c6ec49b0dd652814457616f7785fae54 to your computer and use it in GitHub Desktop.
Async event polling in JavaScript. Just a proof-of-concept, not recommended for serious development, even though it's pretty convenient.
class Queue {
#start = 0
#end = 0
#len = 0
#cap = 1 << 10
#cap_mask = this.#cap - 1
#data = new Array(this.#cap)
enqueue(item) {
if (this.#len == this.#cap) {
this.#data = this.#data.concat(this.#data)
this.#end += this.#cap
this.#cap <<= 1
this.#cap_mask = (this.#cap_mask << 1) | 1
}
this.#start = (this.#start - 1) & this.#cap_mask
this.#len++
this.#data[this.#start] = item
}
dequeue() {
if (this.#len == 0) return null
this.#end = (this.#end - 1) & this.#cap_mask
this.#len--
return this.#data[this.#end]
}
}
function createPoller(elem, type) {
const events = new Queue()
const resolvers = new Queue()
elem.addEventListener(type, e => {
const r = resolvers.dequeue()
if (r) return r(e)
events.enqueue(e)
})
return () => {
const e = events.dequeue()
if (e) return Promise.resolve(e)
return new Promise(res => resolvers.enqueue(res))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment