闭包:使用记忆法

2025-06-04

闭包:使用记忆法

函数式编程的核心原则之一是,函数每次输入相同的值时都应该返回相同的值。记忆化是一种让递归或迭代函数运行更快的做法。这通常是通过缓存函数处理的值来实现的。

const multiplyCache = {}

const multiplyBy2 = num => {
  if (multiplyCache[num]) {
    return multiplyCache[num]
  }
  const total = num * 2
  console.log('Loading...') // To represent this process taking time
  multiplyCache[num] = total
  return total
}

console.log(multiplyBy2(5))
console.log(multiplyBy2(2))
console.log(multiplyBy2(5))
console.log(multiplyBy2(2))

// The first time we run the function with 5 and 2, we get Loading... 
// before we get the total. The second time with each, we fetch 
// it from the cache instead.
Enter fullscreen mode Exit fullscreen mode

这个非常基础的例子说明了缓存的工作原理。我们将结果存储在对象中,以便稍后引用,从而大大缩短了调用时间。

那么闭包在其中起什么作用呢?嗯,它们通过记忆赋予我们更多的权力,让我们能够保留缓存的值并保护它们。

const specialNum = () => {
  let cache = {}
  return name => {
    if (cache[name]) {
      return cache[name]
    }
    console.log('Generating special number...') // To represent this process taking time
    const rand = Math.floor(Math.random() * 3 + 1)
    cache[name] = rand
    return rand
  }
}

const generateSecretNum = specialNum()

const specialNumBrian = generateSecretNum('brian')
const specialNumPiper = generateSecretNum('piper')

console.log(specialNumBrian) // Will generate, since it's the first time.
console.log(specialNumPiper) // Will generate, since it's the first time.
console.log(specialNumBrian) // Returns cached value.
console.log(specialNumPiper) // Returns cached value.

// Like above, we only get "Generating secret..." the first time. 
// The key difference here is, our cache variable is protected 
// inside of our closure and can't be accessed 
// from the outside.
Enter fullscreen mode Exit fullscreen mode

我希望你能理解闭包与记忆化相结合是多么强大的组合。通过返回缓存值,我们让函数运行得更快。同时,我们也通过使用闭包来保护缓存。

我想说,这是一件非常棒的工具!

文章来源:https://dev.to/bbarbour/closures-using-memoization-3597
PREV
JavaScript 开发人员面试问题:提升、原型继承以及属性与属性
NEXT
Angular ❤️ Bazel 离开 Angular Labs 我们学到了什么 推广 Bazel 这对我意味着什么?