Created
March 30, 2024 13:54
-
-
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.
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 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