How to implement memoize function | JavaScript Interview Question | Problem Solving
At times, we want to boost the performance of our applications. Memoization is a common technique to do so. In React, we have seen React.memo
and useMemo
.
In this question, you need to implement the memoizeOne
function provided by the memoize-one library on your own. The function should cache only the result of the most recent arguments.
function add(a, b) {
return a + b;
}
const memoizedAdd = memoizeOne(add);
memoizedAdd(1, 2);
// add function: is called
// [new value returned: 3]
memoizedAdd(1, 2);
// add function: not called
// [cached result is returned: 3]
memoizedAdd(2, 3);
// add function: is called
// [new value returned: 5]
memoizedAdd(2, 3);
// add function: not called
// [cached result is returned: 5]
memoizedAdd(1, 2);
// add function: is called
// [new value returned: 3]
// 👇
// While the result of `add(1, 2)` was previously cached
// `(1, 2)` was not the *latest* arguments (the last call was `(2, 3)`)
// so the previous cached result of `(1, 3)` was lost
The Default equality check function should be a shallow comparison on array items with strict equal ===
.
To read more about the behaviour of memoizeOne
, read here:
https://github.com/alexreardon/memoize-one#function-argument-equality
Bonus:
You can also implement the functionality of passing a custom function for checking the equality of two sets of arguments.
Syntax:
const memoized = memoizeOne(fn, isEqual);
Read more here: https://github.com/alexreardon/memoize-one#custom-equality-function