Skip to content

Instantly share code, notes, and snippets.

@donabrams
Last active November 9, 2017 16:24
Show Gist options
  • Save donabrams/1b809159e8067aafdd7241a0466e185e to your computer and use it in GitHub Desktop.
Save donabrams/1b809159e8067aafdd7241a0466e185e to your computer and use it in GitHub Desktop.
Memoizer
let set = (cache, val, k, ...rest) => {
if (rest && rest.length) {
if (!cache.has(k)) {
cache.set(k, new Map());
}
set(cache.get(k), val, ...rest);
} else {
cache.set(k, val);
}
};
let get = (cache, k, ...rest) => {
if (cache.has(k)) {
return rest && rest.length ? get(cache.get(k), ...rest) : cache.get(k);
} else {
return undefined;
}
};
let memoizeHelper = (f) => {
const cache = new Map();
return (...args) => {
let toRet = get(cache, ...args);
if (!toRet) {
toRet = f(...args);
set(cache, toRet, ...args);
}
return toRet;
};
};
let memoize = (memos) => {
return Object.keys(memos).reduce((acc, k) => {
acc[k] = memoizeHelper(memos[k]);
return acc;
}, {});
};
let memo = memoize({
a: x => x*2,
b: y => y^y, //Notice the bug here, should be `Math.pow(3, 3)`
c: (x, y) => Math.pow(x,y),
d: (x, y) => memo.b(x) + memo.b(y),
});
console.log(memo.a(2));
console.log(memo.b(3));
console.log(memo.c(4, 4));
console.log(memo.d(3, 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment