Created
July 4, 2019 17:07
-
-
Save mminer/c7f4e3211970f56dc30fd26d40551e61 to your computer and use it in GitHub Desktop.
Simple least-recently inserted cache.
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
export default class LeastRecentlyInsertedCache<T> implements Iterable<T> { | |
private maxSize: number; | |
// Set objects maintain insertion order, making them appropriate for keeping track of when values | |
// are added relative to each other. | |
private set = new Set<T>(); | |
constructor(maxSize: number) { | |
this.maxSize = maxSize; | |
} | |
[Symbol.iterator]() { | |
return this.set.values(); | |
} | |
add(item: T) { | |
// Ensure the item is placed at the end if the cache already contains it. | |
this.set.delete(item); | |
this.set.add(item); | |
// Remove the first (i.e. oldest) value if adding a new one pushes the set beyond its max size. | |
if (this.set.size > this.maxSize) { | |
const firstValue = this.set.values().next().value; | |
this.set.delete(firstValue); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment