函数缓存

  • 把参数和对应的结果数据存在一个对象中,调用时判断参数对应的数据是否存在,存在就返回对应的结果数据,否则就返回计算结果
  1. const memoize = function (func, content) {
  2. let cache = Object.create(null)
  3. content = content || this
  4. return (...key) => {
  5. if (!cache[key]) {
  6. cache[key] = func.apply(content, key)
  7. }
  8. return cache[key]
  9. }
  10. }
  11. function add(a, b) {
  12. return a + b
  13. }
  14. const calc = memoize(add)
  15. const num1 = calc(100, 200)
  16. const num2 = calc(100, 200) // 缓存得到的结果