Topic describes
Title address
Thought analysis
The memo function is not executed if the function parameters are the same before and after the react. memo(functionalComponent) comparison. A closure function needs to be defined. In the closure variable, props is stored. In the execution function, the variables contain props
function memo(fn) {
const map = new Map(a);return function (. args) {
/ / get the key
if (map.has(args)) {
return map.get(args);
}
/ / assignment keymap.set(args, fn(... args));return fn(...args);
}
}
Copy the code
At this stage, we have basically implemented the cache function, but there are still two requirements that need to be met:
- if
memo
The function takes a second argumentcallback
The cached key is the return value of the callback function - Binding this
function memo(fn, resolver) {
const map = new Map(a);return function (. args) {
// Map key is the reference type, so args.join()
constkey = resolver ? resolver(... args) : args.join('_');
/ / get the key
if (map.has(key)) {
return map.get(key);
}
/ / assignment key
const cache = fn.call(this. args) map.set(key, cache);returncache; }}// test1
function add(a, b) {
return a + b;
}
const memod = memo(add);
console.log(memod(1.2));
console.log(memod(1.2));
// test2
function funcThis(b){
return `The ${this.a}_${b}`;
}
const memoed = memo(funcThis);
const a = { a: 1, memoed }; / / 1 _2
Copy the code
At this point, we have completed the memo() but running out of memory if we use the cache indefinitely, so we implement Memoize-One based on the memo to cache only the last time. A map can have a maximum of two map objects. You only need to delete the first cache object if the map.size is greater than 1
// memoizeOne
if (map.size > 1) {
map.delete(map.keys().next.value);
}
Copy the code
AC code
/ * * *@param {Function} func
* @param {(args:[]) => string } [resolver] - cache key generator
*/
function memo(func, resolver) {
// your code here
const map = new Map(a);return function (. args) {
constkey = resolver ? resolver(... args) : args.join('_');
if (map.has(key)) {
console.log('is memoize', args);
return map.get(key);
}
const cache = func.call(this. args) map.set(key, cache);returncache; }}Copy the code
conclusion
This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign