Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Created May 14, 2023 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordonbrander/1cbff0dd854d49bc37ebe74506e8bc46 to your computer and use it in GitHub Desktop.
Save gordonbrander/1cbff0dd854d49bc37ebe74506e8bc46 to your computer and use it in GitHub Desktop.
async-mailbox.js - async generator publisher
export const sleep = ms => new Promise(resolve => {
setTimeout(resolve, ms)
})
export const hz = x => (1/x * 1000)
const complete = Symbol('complete')
export class Mailbox {
#buffer = []
constructor(rate=16, max=500) {
this.rate = rate
this.max = max
}
send(value) {
if (this.#buffer.length < this.max) {
this.#buffer.push(value)
return true
}
return false
}
async next() {
while (true) {
if (this.#buffer.length > 0) {
let value = this.#buffer.shift()
return {value, done: false}
}
await sleep(this.rate)
}
}
[Symbol.asyncIterator]() {
return this
}
}
export const EventMailbox = (element, event) => {
let mailbox = new Mailbox()
element.addEventListener(event, event => {
mailbox.send(event)
})
return mailbox
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment