Skip to content

Instantly share code, notes, and snippets.

@justinobney
Created May 9, 2018 13:40
Show Gist options
  • Save justinobney/7f501ba1a34d61b3dcfb51fa54e92822 to your computer and use it in GitHub Desktop.
Save justinobney/7f501ba1a34d61b3dcfb51fa54e92822 to your computer and use it in GitHub Desktop.
recursive-memoize
import faker from "faker";
import { isUndefined, times, shuffle} from "lodash";
// const data = shuffle(
// times(10, x => ({
// order: x,
// id: faker.internet.email(),
// name: faker.name.findName()
// }))
// );
// const indexByKey = memoize((collection, key, isDictionary = true) => {
// console.log('indexByKey');
// return Object.values(collection).reduce((acc, value) => {
// acc[value[key]] = value;
// return acc;
// }, isDictionary ? {} : []);
// });
// console.log(indexByKey(data, "id"));
// console.log(indexByKey(data, "order", false));
const cache = new Map();
const getCacheResult = (cache, currentKey, ...nestedKeys) => {
if(!cache.has(currentKey)){
return undefined;
} else if(nestedKeys.length === 0){
return cache.get(currentKey).result;
} else {
return getCacheResult(cache.get(currentKey).cache, ...nestedKeys)
}
}
const setCacheResult = (result, cache, currentKey, ...nestedKeys) => {
let cacheLevel;
if(!cache.has(currentKey)){
cacheLevel = {
cache: new Map()
};
cache.set(currentKey, cacheLevel);
} else {
cacheLevel = cache.get(currentKey);
}
if(nestedKeys.length){
setCacheResult(result, cacheLevel.cache, ...nestedKeys);
} else {
cacheLevel.result = result;
}
}
const memoizeR = (fn) => (...args) => {
const cachedResult = getCacheResult(cache, ...args);
if(cachedResult !== undefined){
return cachedResult;
}
const result = fn(...args);
setCacheResult(result, cache, ...args);
return result;
}
let uuid = 1;
const fakeFunction = (x,y) => `${uuid++} -- ${Math.random()}`;
const betterFakeFunction = memoizeR(fakeFunction)
console.log(betterFakeFunction(1,2));
console.log(betterFakeFunction(1,2));
console.log(betterFakeFunction(1,3));
console.log(betterFakeFunction(2,2));
console.log(betterFakeFunction(2,3));
console.log(betterFakeFunction(2,3,4));
console.log(betterFakeFunction(2,3,4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment