You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
As promised. As JS doesn't have a base ordered map, we instead use a history array that cross-references a key-value store. Touching the store will update the history, and when we hit the limit, we search the history to evict old entries from the store. This requires some semi-regular garbage collection on the history array to avoid accumulating the access records.
classLeastRecentlyUsedCache{
#store;
#history;
#limit;
#callback;constructor(limit,{ callback =null}={}){this.#store =newMap;this.#history =[];this.#limit =limit;this.#callback =(callback==null ? x=>{} : callback);}
#gc(){if(this.#history >this.#limit *5){letreplacement=[];for(constxofthis.#history){if(x!==null){this.#store.get(x).last_access=replacement.length;replacement.push(x);}}this.#history =replacement;}}
#touch(key,exists){// Don't bother updating it if it's already the last-accessed.if(exists.last_access!==this.#history -1){this.#history[exists.last_access]=null;exists.last_access=this.#history.length;}this.#gc();this.#history.push(key);}set(key,value){letexists=this.#store.get(key);if(typeofexists!=="undefined"){this.#touch(key,exists);exists.value=value;}else{// Flushing.if(this.#store.size==this.#limit){leti=0;while(i<this.#history.length){letx=this.#history[i];if(x!==null){this.#history[i]=null;this.#callback(this.#store.get(x).value);this.#store.delete(x);break;}i++;}}this.#gc();this.#store.set(key,{value: value,last_access: this.#history.length});this.#history.push(key);}}get(key){letexists=this.#store.get(key);if(typeofexists==="undefined"){thrownewError("failed to find key '"+key+"' in the cache");}this.#touch(key,exists);returnexists.value;}delete(key){letexists=this.#store.get(key);if(typeofexists==="undefined"){thrownewError("failed to find key '"+key+"' in the cache");}this.#history[exists.last_access]=null;this.#callback(exists.value);this.#store.delete(key);return;}};
As promised. As JS doesn't have a base ordered map, we instead use a history array that cross-references a key-value store. Touching the store will update the history, and when we hit the limit, we search the history to evict old entries from the store. This requires some semi-regular garbage collection on the history array to avoid accumulating the access records.
Usage is something like:
Which gives the expected eviction:
The text was updated successfully, but these errors were encountered: