memoize

Medium · Functional Programming Concepts · 3 test cases

Create a function that memoizes the results of another function. A memoized function stores the results of expensive function calls and returns the cached result when the same inputs occur again.

Examples

const slowSquare = (num) => { /* Imagine this is a slow op */ return num * num; };
const fastSquare = memoize(slowSquare);
fastSquare(5); // computes
fastSquare(5); // returns from cache

Starter code

function memoize(fn) {

}

Complexity of the optimal solution

Time O(1) amortized, space O(k). After the first call for a given set of inputs, subsequent calls are O(1) as they retrieve from the cache. The space complexity is O(k), where k is the number of unique inputs cached.

Solve memoize in the browser