简体   繁体   English

JavaScript编写一个缓存功能的功能(记忆)

[英]JavaScript write a function which caches a function(memoization)

I have been asked this question and I wasn't sure how I can target this. 我被问到这个问题,我不确定该如何解决。

Question: 题:

Write a cache function which caches a function and returns a result if it was already executed in the past. 编写一个缓存函数,该函数缓存一个函数并返回结果(如果过去已执行过该结果)。

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

My attempt: 我的尝试:

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;
    }
}

But I'm not able to understand how to get the arguments in one function inside another function? 但是我不明白如何在另一个函数中的一个函数中获取参数 (The person told me that I need to use closure to get it) (那个人告诉我,我需要使用闭包来获取它)

Can someone enlighten me? 有人可以启发我吗?

It's not cacheFunction(Fibonacci(20)) , it's cacheFunction(Fibonacci)(20) . 它不是cacheFunction(Fibonacci(20)) ,它是cacheFunction(Fibonacci)(20) You indeed cannot get the parameters of Fibonacci , you cannot alter that function to somehow access them. 您确实无法获得Fibonacci的参数,也无法更改该函数以某种方式访问​​它们。 What cacheFunction is supposed to do is to construct a new function that provides the same functionality as the passed-in funct (ie Fibonacci in your case) by wrapping around it. 什么cacheFunction是应该做的是建立一个新的功能 ,它提供了相同的功能传入的funct (即Fibonacci围绕在你的情况下)的包装。 In the wrapper function that will eventually get called with the input (eg 20 ) you can access the arguments and check the cache for their values, and potentially pass them on to funct . 在最终将使用输入(例如20 )调用的包装函数中,您可以访问参数并检查高速缓存中的值,并有可能将其传递给funct

Memoization/caching technique is available as part of underscore.js. 备注/缓存技术可作为underscore.js的一部分使用。 You can directly use it if needed. 您可以根据需要直接使用它。 I also added a sitepoint article which walks you through implementing memoization in JS. 我还添加了一个站点点文章,该文章引导您完成在JS中实现备忘录的过程。

Implementing Memoization in JavaScript 在JavaScript中实现记忆

memoize in underscorejs 在underscorejs中记住

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM