lodash源码分析之memoizeCapped

84 阅读1分钟

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

依赖

import memoize from '../memoize.js'

源码分析

memoize函数的作用是提供一个带缓存功能的func函数。

memoizeCapped函数是对memoize的一个扩展,给缓存加了一个大小限制,超出限制则清空缓存。

const MAX_MEMOIZE_SIZE = 500

/**
 * A specialized version of `memoize` which clears the memoized function's
 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
 *
 * @private
 * @param {Function} func The function to have its output memoized.
 * @returns {Function} Returns the new memoized function.
 */
function memoizeCapped(func) {
  const result = memoize(func, (key) => {
    const { cache } = result
    if (cache.size === MAX_MEMOIZE_SIZE) {
      cache.clear()
    }
    return key
  })

  return result
}

定义缓存大小MAX_MEMOIZE_SIZE,初始化为500.

首先,调用memoize函数将func函数缓存,并传入一个箭头函数。该函数的作用,除了返回缓存用的key,还判断了缓存大小,超出上限则清空缓存。

接着,把memoize函数的调用结果赋值给result,并返回。