SHARE
TWEET

Untitled

a guest Jul 16th, 2019 56 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export default class LeastRecentlyInsertedCache<T> implements Iterable<T> {
  2.   private maxSize: number;
  3.  
  4.   // Set objects maintain insertion order, making them appropriate for keeping track of when values
  5.   // are added relative to each other.
  6.   private set = new Set<T>();
  7.  
  8.   constructor(maxSize: number) {
  9.     this.maxSize = maxSize;
  10.   }
  11.  
  12.   [Symbol.iterator]() {
  13.     return this.set.values();
  14.   }
  15.  
  16.   add(item: T) {
  17.     // Ensure the item is placed at the end if the cache already contains it.
  18.     this.set.delete(item);
  19.     this.set.add(item);
  20.  
  21.     // Remove the first (i.e. oldest) value if adding a new one pushes the set beyond its max size.
  22.     if (this.set.size > this.maxSize) {
  23.       const firstValue = this.set.values().next().value;
  24.       this.set.delete(firstValue);
  25.     }
  26.   }
  27. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top