🔗LC2623 🟡 Medium 🧩 Pattern – Function Transformations
📅 Day 11/30 Days of JavaScript
Given a function fn
, return a memoized version of that function.
A memoized function is a function that will never be called twice with the same inputs. Instead, it will return a cached value.
You can assume there are 3 possible input functions: sum
, fib
, and factorial
.
sum
accepts two integersa
andb
and returnsa + b
. Assume that if a value has already been cached for the arguments(b, a)
wherea != b
, it cannot be used for the arguments(a, b)
. For example, if the arguments are(3, 2)
and(2, 3)
, two separate calls should be made.fib
accepts a single integern
and returns1
ifn <= 1
orfib(n - 1) + fib(n - 2)
otherwise.factorial
accepts a single integern
and returns1
ifn <= 1
orfactorial(n - 1) * n
otherwise.
Example
Input:
fnName = "sum"
actions = ["call","call","getCallCount","call","getCallCount"]
values = [[2,2],[2,2],[],[1,2],[]]
Output: [4,4,1,3,2]
Explanation:
const sum = (a, b) => a + b;
const memoizedSum = memoize(sum);
memoizedSum(2, 2); // "call" - returns 4. sum() was called as (2, 2) was not seen before.
memoizedSum(2, 2); // "call" - returns 4. However sum() was not called because the same inputs were seen before.
// "getCallCount" - total call count: 1
memoizedSum(1, 2); // "call" - returns 3. sum() was called as (1, 2) was not seen before.
// "getCallCount" - total call count: 2
Solution
This is similar to React.useMemo in React which is used to prevent expensive computations between renders and repetitive function calls.
/**
* @param {Function} fn
* @return {Function}
*/
function memoize(fn) {
const cache = {};
return function (...args) {
const key = String(args);
if (key in cache) {
return cache[key];
} else {
const result = fn(...args)
cache[key] = result;
return result;
}
}
}
/**
* let callCount = 0;
* const memoizedFn = memoize(function (a, b) {
* callCount += 1;
* return a + b;
* })
* memoizedFn(2, 3) // 5
* memoizedFn(2, 3) // 5
* console.log(callCount) // 1
*/