Created
May 8, 2024 10:43
-
-
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
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 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