Created
July 11, 2020 19:37
-
-
Save funfunction/944a939d165fd2357bd8a84967a3f192 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
@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