Loading

「跟着渡一学前端」Lodash——手写memoize函数

学习资源

完整代码

function memoize(func, resolver) {
  const memoized = function (...args) {
    const key = resolver ? resolver.apply(this, args) : args[0];
    if (memoized.cache.has(key)) {
      return memoized.cache.get(key);
    }
    const result = func.apply(this, args);
    memoized.cache.set(key, result);
    return result;
  }

  memoized.cache = new WeakMap();

  return memoized;
}

知识细节

  1. 该函数做了什么事情?

    • 可以做缓存(即在参数相同的时候,会取上一次返回结果,不会再调用方法);
    • 可以通过.cache.set设置缓存key对应的值。
  2. 逻辑拆解

    1. 基础结构:传入一个函数,返回一个函数

    2. 功能实现

      1. 实现可以通过.cache.set方法设置缓存功能

      2. 实现调用函数时,尽量从缓存结果中获取缓存

      3. 处理函数第二个参数功能。--用于规定缓存的键。

posted @ 2025-02-17 23:31  lao-jiawei  阅读(77)  评论(0)    收藏  举报