Created
May 16, 2025 01:43
-
-
Save night-fury-rider/7e415d74233908ffc5760e2828becddc to your computer and use it in GitHub Desktop.
Design Pattern - Memoization
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 memoize = (func) => { | |
const cache = {}; | |
return (...args) => { | |
const key = args.toString(); | |
if (cache[key]) { | |
console.log(`Getting from the cache for ${key}`); | |
return cache[key]; | |
} else { | |
console.log(`Getting from actual function for ${key}`); | |
cache[key] = func(...args); | |
return cache[key]; | |
} | |
}; | |
}; | |
const slowAdd = (a, b) => { | |
// Simulating a slow computation | |
for (let i = 0; i < 1e9; i++); | |
return a + b; | |
}; | |
const fastAdd = memoize(slowAdd); | |
console.log(fastAdd(2, 3)); | |
console.log(fastAdd(2, 3)); | |
console.log(fastAdd(4, 5)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment