Skip to content

Instantly share code, notes, and snippets.

@funfunction
Created July 11, 2020 19:37
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 funfunction/944a939d165fd2357bd8a84967a3f192 to your computer and use it in GitHub Desktop.
Save funfunction/944a939d165fd2357bd8a84967a3f192 to your computer and use it in GitHub Desktop.
/**
@func
Map object factory
@return {Map}
*/
export const createLruMap = () => new Map();
/**
@func curry
set a key/value pair to the back of the queue
@notes
curried to set the Map source and queue limit
enforces a max size of the queue
@param {Map} o
@param {number} limit
@return {(k: string, v: *) => void}
*/
export const writeMap = (o, limit) => (k, v) => {
if (o.size >= limit) {
for (let [k] of o) { //evict (delete) the oldest key/value pair entry
o.delete(k);
break;
}
}
o.set(k, v);
};
/**
@func curry
get a value mapping to the supplied key
@notes
curried to set the map source
@param {Map} o Map object
@return {(k: string) => *} returns the value of a key/value pair
*/
export const readMap = o => k => {
const v = o.get(k); // move the k to the front, to indicate it's the most recently read item
o.delete(k);
o.set(k, v);
return o.get(k);
}
//@tests
//timeStart();
//const iter = 1e6;
//for (let i = 0; i < iter; i++) {
const lruMap = createLruMap();
const w3 = writeMap(lruMap, 3);
const r3 = readMap(lruMap);
w3("a", "Apple");
w3("b", "Banana");
w3("c", "Carrot");
r3("a"); //Apple - change {a,b,c} {oldest...newest} -> {b,c,a}
w3("d", "Donut"); //should evict b
r3("b"); //should be null
r3("c"); //Carrot
//}
//timeLog(); //1.9 for 1e6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment