JavaScript编写一个缓存函数的函数(memoization)

时间:2017-03-16 01:15:18

标签: javascript

我被问到这个问题,而且我不确定如何定位这个问题。

问题:

  

编写缓存函数,缓存函数并返回结果if   它已经在过去执行过了。

Let's say if there's a function Fibonacci(20) = 6765

cacheFunction(Fibonacci(20)) // it should not execute the function instead return 6765. 

But if i give cacheFunction(Fibonacci(21)) //It's not cached, execute the function

我的尝试:

function cacheFunction(funct) {

    var obj = {};

    if (obj.hasOwnProperty(funct)) { //checking if the argument is in the object?
        return obj[funct];
    } else { //if not present, then execute the function, store it in cache and return the value.
        obj[funct];
        return funct;
    }
}

但是我无法理解如何在另一个函数中的一个函数中获取参数? (该人告诉我,我需要使用封闭来获取它)

有人可以启发我吗?

2 个答案:

答案 0 :(得分:1)

不是cacheFunction(Fibonacci(20)),而是cacheFunction(Fibonacci)(20)。你确实无法获得Fibonacci的参数,你不能改变该函数以某种方式访问​​它们。 cacheFunction应该做的是构建一个新函数,它提供与传入的funct相同的功能(在您的情况下为Fibonacci)环绕它。在最终将使用输入调用的包装函数(例如20)中,您可以访问参数并检查缓存中的值,并可能将它们传递给funct

答案 1 :(得分:-2)

记忆/缓存技术作为underscore.js的一部分提供。如果需要,您可以直接使用它。我还添加了一篇站点文章,引导您在JS中实现memoization。

Implementing Memoization in JavaScript

memoize in underscorejs