Skip to content

Instantly share code, notes, and snippets.

@night-fury-rider
Last active May 15, 2026 02:30
Show Gist options
  • Select an option

  • Save night-fury-rider/7e415d74233908ffc5760e2828becddc to your computer and use it in GitHub Desktop.

Select an option

Save night-fury-rider/7e415d74233908ffc5760e2828becddc to your computer and use it in GitHub Desktop.
Optimization - Memoization
const memoize = (callback, limit = 100, delimiter = "\u00B7") => {
if (typeof callback !== "function") {
throw new TypeError("Memoize expects a function");
}
const cache = new Map();
return (...args) => {
const cacheKey = args.join(delimiter); // To get key without collision
if (cache.has(cacheKey)) {
console.log(`Retrieving from cache for ${cacheKey}`);
return cache.get(cacheKey);
}
console.log(`******* Calculating result for ${cacheKey} *******`);
// If cache reach the limit, delete the first (oldest) entry
if (cache.size >= limit) {
cache.delete(cache.keys().next().value);
}
const result = callback(...args);
cache.set(cacheKey, result);
return result;
};
};
const memoizedFactorial = memoize(function factorial(n) {
return n <= 1 ? 1 : n * memoizedFactorial(n - 1);
});
console.log(`Factorial of 11: ${memoizedFactorial(11)}`);
console.log(`Factorial of 6: ${memoizedFactorial(3)}`);
console.log(`Factorial of 7: ${memoizedFactorial(3)}`);
console.log(`Factorial of 11: ${memoizedFactorial(11)}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment