Skip to content

Instantly share code, notes, and snippets.

@KOBA789
Created September 16, 2024 08:52
Show Gist options
  • Save KOBA789/3895273199a29cc50482a8a231ec4d43 to your computer and use it in GitHub Desktop.
Save KOBA789/3895273199a29cc50482a8a231ec4d43 to your computer and use it in GitHub Desktop.
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