Skip to content

Instantly share code, notes, and snippets.

@night-fury-rider
Created May 16, 2025 01:43
Show Gist options
  • Save night-fury-rider/7e415d74233908ffc5760e2828becddc to your computer and use it in GitHub Desktop.
Save night-fury-rider/7e415d74233908ffc5760e2828becddc to your computer and use it in GitHub Desktop.
Design Pattern - Memoization
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