Memoize with Closure Cache
Write a JavaScript function that creates a memoized version of a given function using a closure-based cache object. The memoized function stores results of previous calls in a cache and returns the cached result when the same input is provided again, avoiding redundant computation.
Memoization is an optimization technique where function results are cached based on their arguments. A closure maintains the cache object across multiple calls to the memoized function. Before computing a result, the memoized function checks if the argument already exists as a key in the cache. If so, it returns the cached value without calling the original function.
Closures in JavaScript allow functions to retain access to variables from their outer scope even after the outer function has returned. In memoization, the cache object is defined in the outer function's scope and persists for the lifetime of the memoized function. Each call to the memoized function can read from and write to this cache.
Time complexity is O(1) for cached lookups and O(k) for the first call where k is the time of the original function. Space complexity is O(n) where n is the number of unique arguments. This space-time tradeoff is the essence of memoization.
Edge cases include calling the memoized function with the same argument multiple times (returns cached result, original function not called again), different arguments (computes and caches each), and ensuring the cache does not grow unbounded for infinite unique inputs.
Example Input & Output
Different inputs, all computed
Zero cached after first call
Same input 3 times, cached after first
Mixed: 5 cached on third call
All cached after first
Algorithm Flow

Solution Approach
Best Answers
function memoize(fn) {
var cache = {};
return function(x) {
if (cache[x] !== undefined) return cache[x];
cache[x] = fn(x);
return cache[x];
};
}
function double(x) { return x * 2; }
function solution(calls) {
var memoized = memoize(double);
var results = [];
for (var i = 0; i < calls.length; i++) {
results.push(memoized(calls[i]));
}
return results;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
