Skip to content

Instantly share code, notes, and snippets.

@danew
Created May 8, 2024 10:43
Show Gist options
  • Save danew/a4278415101d530368d190fba69e6c12 to your computer and use it in GitHub Desktop.
Save danew/a4278415101d530368d190fba69e6c12 to your computer and use it in GitHub Desktop.
Set with timestamps of when values were added with a purge by age helper
export class TimeSet {
private items: Map<string, number>;
constructor() {
this.items = new Map();
}
add(item: string) {
const timestamp = Date.now();
this.items.set(item, timestamp);
}
delete(item: string) {
return this.items.delete(item);
}
has(item: string) {
return this.items.has(item);
}
getTimestamp(item: string) {
return this.items.get(item) || null;
}
clear() {
this.items.clear();
}
size() {
return this.items.size;
}
*entries() {
for (const [item, timestamp] of this.items) {
yield { item, timestamp };
}
}
*[Symbol.iterator]() {
yield* this.entries();
}
purgeOlderThan(threshold: number) {
const now = Date.now();
const result = [];
for (const [item, timestamp] of this.items) {
if (now - timestamp > threshold) {
result.push({ item, timestamp });
this.items.delete(item);
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment