Skip to content

Instantly share code, notes, and snippets.

@techfort
Last active August 23, 2016 14:54
Show Gist options
  • Save techfort/8e359de25e582663f67c38fbc8f80509 to your computer and use it in GitHub Desktop.
Save techfort/8e359de25e582663f67c38fbc8f80509 to your computer and use it in GitHub Desktop.
const add = (a, b) => (a + b);
const cachingFunc = (cacheObj = {}) => {
const cache = cacheObj;
return (a, b) => {
let hash = `${a}:${b}`;
if (!cache[hash]) {
console.log('Computing result');
cache[hash] = add(a, b);
} else {
console.log('Skipping computation');
}
return cache[hash];
}
}
console.log('Test without pre-existing cache');
const cachingAdd = cachingFunc();
cachingAdd(3, 4);
cachingAdd(3, 5);
cachingAdd(3, 4);
const cachingAddv2 = cachingFunc({
'3:7': 10,
'4:2': 6
});
console.log('Test with existing cache');
cachingAddv2(3, 7);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment