Created
October 20, 2021 09:33
-
-
Save burakozturk16/70399c3da1e3ed2e88a4446b4b8bf591 to your computer and use it in GitHub Desktop.
Javascript function cache
This file contains 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 memoize = (fn) => { | |
let cache = {}; | |
return (...args) => { | |
let n = fn(...args); | |
if (n in cache) { | |
console.log('Result from cache', cache[n]); | |
return cache[n]; | |
} | |
else { | |
console.log('Result from execute', fn(...args)); | |
let result = fn(...args); | |
cache[n] = result; | |
return result; | |
} | |
} | |
} | |
// for testing.. | |
const add = (a,b) => (a+b); | |
const mul = (a,b) => (a*b); | |
const memoizedAdd = memoize(add); | |
const memoizedMul = memoize(mul); | |
memoizedAdd(1,2); | |
memoizedAdd(1,2); | |
memoizedMul(3,5); | |
memoizedMul(3,5); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment