gpt4 book ai didi

javascript - Memoize 函数传递函数并返回函数 JavaScript

转载 作者:行者123 更新时间:2023-11-30 11:47:55 26 4
gpt4 key购买 nike

我在使用此功能时遇到多个问题。这是数据结构和算法类(class)的附加问题的一部分,我在这个问题上投入了很多时间,我真的很想让它工作并了解发生了什么。

有一个主要问题,引起了几个小问题……这个问题的名字叫JavaScript。我们以前从未用 JavaScript 编程过,但出于某种原因我们不得不使用它。

函数必须通过测试(这个和斐波那契),其结构如下:

var fn = (n) => 2 * n
var m_fn = memoize(fn)
expect(m_fn(18)).to.equal(fn(18))

所以我必须将我想要内存的函数作为参数传递给内存函数,内存函数必须返回一个函数。我不允许以任何其他方式这样做。

我阅读了所有内容并研究了 memoize 函数,但所有的实现都采用了不同的方法。

基本上,我明白我必须做什么,但我不太明白怎么做。我知道 memoize 函数应该做什么,但我不明白如何使用我的 memoize 函数调整原始函数。这是我目前拥有的/我没有的:

我知道这是错误的。但我想我错过了一些重要的东西。我应该返回一个函数,但我正在返回值...

在测试中,它写成 var m_fn = memoize(fn),所以 memoize 函数传递 fn,然后返回一个新函数,但在我的 memoize 中,我返回 fn(n) 的值,所以我在做一些事情错了……

/**
* Creates a memoized version of the function fn. It is assumed that fn is a referentially transparent
* function.
* @param {function} fn Some referentially transparent function that takes a basic datatype (i.e. number / string)
* @returns {function} A new function that is the memoized version of fn. It never calculates the result of
* a function twice.
*/
memoize: (fn) => { //here we enter the function that we want to memoize
var memory = []; //we need to create an array to hold the previously calculated values, length n (parameter of fn)

if(this.n > memory.length){ //Check to see if this particular value is in the array already.
return memory[this.n]; //How do I access the integer parameter that was passed through fn though? Is this correct?
} else{ // if not, we want to save it and return it
var result = fn(this.n);
memory.push(result);
return result;
}

最佳答案

确实,您需要返回一个函数。

其次,数组不是内存的理想结构,因为在其中查找参数值需要线性时间。我建议使用 Map为此,这是此类目的的理想选择。它具有 has()get()set() 方法,这些方法在近乎恒定的时间内运行:

function memoize(fn) {
var memory = new Map();
return function(arg) {
if (memory.has(arg)) {
console.log('using memory');
return memory.get(arg);
} else {
var result = fn(arg);
memory.set(arg, result);
return result;
}
};
}

var fn = (n) => 2 * n
var m_fn = memoize(fn)

console.log(fn(18));
console.log(m_fn(18));
console.log(m_fn(18)); // outputs also "using memory"

关于javascript - Memoize 函数传递函数并返回函数 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40328694/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com