Last active
August 23, 2016 14:54
-
-
Save techfort/8e359de25e582663f67c38fbc8f80509 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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