Skip to content

Instantly share code, notes, and snippets.

@mminer
Created July 4, 2019 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mminer/c7f4e3211970f56dc30fd26d40551e61 to your computer and use it in GitHub Desktop.
Save mminer/c7f4e3211970f56dc30fd26d40551e61 to your computer and use it in GitHub Desktop.
Simple least-recently inserted cache.
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