JS 中的 Memoized 函数实现。它是如何运作的?

问题描述 投票:0回答:1

我最近在接受一次采访,被问到一个 JavaScript 编码问题。问题是关于函数记忆化的实现。我认为我们需要存储参数和结果来实现这个,我建议 localStorage 因为我想不出另一种方法来存储不限于函数范围的参数(我是 JS 的业余爱好者) 。当我向 ChatGPT 询问这个问题的解决方案时,它提出了以下建议 -

function memoize(func) {
  const cache = new Map(); // Use a Map to store cached results

  return function (...args) {
    const key = JSON.stringify(args); // Create a unique key based on function arguments

    if (cache.has(key)) {
      // If the result is cached, return it
      return cache.get(key);
    } else {
      // Otherwise, compute the result and cache it
      const result = func(...args);
      cache.set(key, result);
      return result;
    }
  };
}

// Example function to be memoized
function expensiveFunction(n) {
  console.log(`Computing for ${n}`);
  return n * 2;
}

// Create a memoized version of the expensive function
const memoizedExpensiveFunction = memoize(expensiveFunction);

console.log(memoizedExpensiveFunction(5)); // Computes and caches for 5
console.log(memoizedExpensiveFunction(5)); // Returns cached result for 5
console.log(memoizedExpensiveFunction(10)); // Computes and caches for 10
console.log(memoizedExpensiveFunction(10)); // Returns cached result for 10

但是,在此,Map 函数用于在函数内部定义,从逻辑上讲,它必须限制在 memoize 函数的范围内,并且不能在连续的函数调用中持续存在。

我尝试运行这段代码,它有效。但是,我无法理解“为什么”它有效。请通过解释其工作原理或提供相关文档的链接来帮助我。我引用的文档没有提及任何有关其范围的内容。另外,请告诉我是否有其他方法可以在 JS 中实现记忆化(面试官提到了“使用 try 数据结构”之类的内容,我不知道这意味着什么)。

javascript javascript-objects javascript-scope
1个回答
0
投票
必须限制在memoize函数的范围内,而不是 坚持连续的函数调用。

你的问题的答案就是这一行

const memoizedExpensiveFunction = memoize(expensiveFunction);

.

在这里,您将创建 

function

的实例并调用

memoize
函数返回的函数。现在
memoize
返回的函数也可以访问在其范围之外定义的变量(闭包)。因此,每当您调用
memoizedExpensiveFunction
时,它都可以看到变量
cache
    

© www.soinside.com 2019 - 2024. All rights reserved.