Created
May 14, 2023 00:46
-
-
Save gordonbrander/1cbff0dd854d49bc37ebe74506e8bc46 to your computer and use it in GitHub Desktop.
async-mailbox.js - async generator publisher
This file contains hidden or 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
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