Created
September 16, 2024 08:52
-
-
Save KOBA789/3895273199a29cc50482a8a231ec4d43 to your computer and use it in GitHub Desktop.
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 CollapsedQueue<K, V> { | |
private jobs: Map<K, V> = new Map(); | |
constructor( | |
private timeout: number, | |
private collapse: (oldValue: V, newValue: V) => V, | |
private doJob: (key: K, value: V) => void, | |
) {} | |
enqueue(key: K, value: V) { | |
if (this.jobs.has(key)) { | |
const old = this.jobs.get(key)!; | |
const merged = this.collapse(old, value); | |
this.jobs.set(key, merged); | |
} else { | |
this.jobs.set(key, value); | |
setTimeout(() => { | |
const value = this.jobs.get(key); | |
this.jobs.delete(key); | |
this.doJob(key, value); | |
}, this.timeout); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment