Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement