The task is to implement memoizeOne().
The boilerplate code
function memoizeOne(func, isEqual) {
// your code here
}
memoizeOneis a lightweight memoization function that caches only the most recent function call result.
Previous arguments, result and context have to be stored. And also need to track if it has been called (subsequent calls should return cached value)
lastArgs = undefined
lastResult = undefined;
lastThis = undefined;
hasBeenCalled = false;
On the first call, mark that the function has been called, store arguments and context, cache and return the result.
if(!hasBeenCalled) {
hasBeenCalled = true;
lastArgs = args;
lastThis = this;
lastResult = func.apply(this, args);
return lastResult;
}
Check if the next function call is the same as the previous
const equalityCheck = isEqual || defaultIsEqual;
Also, ensure that the context of execution is the same
if(this === lastThis && equalityCheck(args, lastArgs)) {
return lastResult;
}
The function to check each function call.
function defaultIsEqual(args1, args2) {
If the length of both arguments are not equal, the functions are not
if(args1.length !== args2.length) {
return false;
}
Check each argument strictly
for(let i = 0; i < args1.length; i++) {
if(args1[i] !== args2[i]) {
return false;
}
}
return true;
The final code
function memoizeOne(func, isEqual) {
// your code here
let lastArgs = undefined;
let lastResult = undefined;
let hasBeenCalled = false;
let lastThis = undefined;
return function (...args) {
if(!hasBeenCalled) {
hasBeenCalled = true;
lastArgs = args;
lastThis = this;
lastResult = func.apply(this, args);
return lastResult
}
const equalityCheck = isEqual || defaultIsEqual;
if(this ===lastThis && equalityCheck(args, lastArgs)) {
return lastResult;
}
lastArgs = args;
lastThis = this;
lastResult = func.apply(this, args);
return lastResult;
}
}
function defaultIsEqual(args1, args2) {
if(args1.length !== args2.length) {
return false;
}
for(let i = 0; i < args1.length; i++) {
if(args1[i] !== args2[i]) {
return false;
}
}
return true;
}
That's all folks!
Top comments (0)