Skip to content

Instantly share code, notes, and snippets.

@vip3r011
Created April 28, 2023 15:11
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 vip3r011/b3a169c873245eff5b27863f56b886aa to your computer and use it in GitHub Desktop.
Save vip3r011/b3a169c873245eff5b27863f56b886aa to your computer and use it in GitHub Desktop.
Memo_cache using a Map
const cache = new Map();
///
function memo() {
let deleteAfterUse = true; // enable cache deletion after use by default
let maxKeys = 32;
const memoFunc = function (value=null) {
const size = cache.size;
if (value) {
if (size >= maxKeys) {
cache.delete(cache.keys().next().value);
}
const key = (size + 1).toString();
const result = JSON.stringify(value);
cache.set(key, result);
return;
}
if (size > 0) {
const randomKey = Array.from(cache.keys())[Math.floor(Math.random() * size)];
const result = cache.get(randomKey);
if (deleteAfterUse) {
cache.delete(randomKey);
}
return JSON.parse(result);
}
return null;
};
memoFunc.fetchByKey = (key) => {
if (cache.has(key)) {
const result = cache.get(key);
if (deleteAfterUse) {
cache.delete(key);
}
return JSON.parse(result);
}
return null;
};
memoFunc.setDeleteAfterUse = (deleteCache = true) => {
deleteAfterUse = deleteCache;
};
memoFunc.setMaxKeys = (MaxKeys = 32) => {
if(MaxKeys>0){
maxKeys = MaxKeys;
}
};
return memoFunc;
}
const myMemo = memo();
myMemo.setMaxKeys(32);
myMemo("value1");
myMemo("value2");
myMemo("value3");
console.log(myMemo.fetchByKey("1"));
myMemo.setDeleteAfterUse(false);
console.log(myMemo());
console.log(myMemo());
console.log(myMemo());
myMemo.setDeleteAfterUse(true);
console.log(myMemo());
console.log(myMemo());
console.log(myMemo());//empty
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment