探秘JavaScript:手写memoize函数全解析

发布于:2025-02-10 ⋅ 阅读:(106) ⋅ 点赞:(0)

memoize 函数主要作用:

memoize 函数主要的作用是缓存函数的计算结果。当一个函数被memoize包装后,它会记住之前传入相同参数时的返回值。

例如,假设有一个计算斐波那契数列的函数fibonacci。斐波那契数列的定义是:F(n)=F(n - 1)+F(n - 2),其中F(0)=0F(1)=1

function fibonacci(n) {
    if (n === 0) {
        return 0;
    }
    if (n === 1) {
        return 1;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

手写实现方法:

class MemoizeMap {
  constructor() {
    this._map = new Map()
    this._weakMap = new WeakMap()
  }
  _isObject(value) {
    return typeof value === 'object' && value !== null
  }
  get(key) {
    if(this._isObject(key)) {
      return this._weakMap.get(key)
    }
    return this._map.get(key)
  }
  set(key, value) {
    if(this._isObject(key)) {
      this._weakMap.set(key, value)
    }
    this._map.set(key, value)
  }
  has(key) {
    if(this._isObject(key)) {
      return this._weakMap.has(key)
    }
    return this._map.has(key)
  }
}

/**
 * 缓存函数
 * @param {*} fn 方法函数
 * @param {*} resolver 存储的 key,可自定义
 * @returns 方法函数结果
 */
function memoize(fn, resolver) {
  if(typeof resolver !== 'function') {
    resolver = (key) => key
  }
  function memoized(...args) {
    const key = resolver(...args)
    if(memoized.cache.has(key)) {
      return memoized.cache.get(key)
    }
    console.log(key, 'key')
    const result = fn.apply(this, args)
    memoized.cache.set(key, result)
    return result
  }
  memoized.cache = new MemoizeMap()
  return memoized
}

const obj1 = {
  a: 1,
  b: 2
}
const other = {
  a: 3,
  b: 4
}

const fn = memoize((obj) => Object.values(obj))
console.log(fn(obj1));

console.log(fn(other));

obj1.b = 'lhc'
console.log(fn(obj1));

fn.cache.set(obj1, ['l', 'h', 'c'])
console.log(fn(obj1));

网站公告

今日签到

点亮在社区的每一天
去签到