lodash源码分析之memoize

95 阅读1分钟

本文为lodash源码分析的第8篇,后续会持续更新这个专题,欢迎指正。

依赖

源码分析

memoize函数的主要作用是为func函数创建一个带缓存功能的版本。如果同一个输入再次被传给该函数,不需要函数计算,而是直接从缓存中取值。

function memoize(func, resolver) {
    if (typeof func !== 'function' || (resolver != null && typeof resolver !== 'function')) {
        throw new TypeError('Expected a function');
    }
    const memoized = function (...args) {
        const key = resolver ? resolver.apply(this, args) : args[0];
        const cache = memoized.cache;

        if (cache.has(key)) {
            return cache.get(key);
        }
        const result = func.apply(this, args);
        memoized.cache = cache.set(key, result) || cache;
        return result;
    };
    memoized.cache = new (memoize.Cache || Map)();
    return memoized;
}

memoize.Cache = Map;

参数说明:

  • func:需要被缓存的函数。
  • resolver:可选参数,确定缓存key的函数。

首先,memoize函数对入参funcresolver的类型做了检查,如果不是function,抛出错误。

其次,定义memoized函数,

  • 获取缓存的`key`:如果`resolver`不为空,调用该函数获取key。如果`resolver`为空,则使用第一个参数作为缓存的`key`
  • 获取缓存`cache`
  • 如果缓存`cache`里有`key`,直接返回缓存结果。
    
  • 否则,调用`func`函数获取计算结果,并把计算结果存入`cache`缓存中,返回计算结果。
    

接着,给memoized函数添加cache属性,并初始化为new (memoize.Cache || Map)()。返回memoize函数。

最后,初始化memoize.Cache,赋值为Map