0

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?

cweiske
  • 30,033
  • 14
  • 133
  • 194
TechnoCorner
  • 4,879
  • 10
  • 43
  • 81
  • 1
    BTW: http://stackoverflow.com/search?q=javascript+memoize – Matt Ball Mar 16 '17 at 01:16
  • Possible duplicate of [Javascript Memoization Explanation?](http://stackoverflow.com/questions/8548802/javascript-memoization-explanation) – m0meni Mar 16 '17 at 01:26

2 Answers2

1

It's not cacheFunction(Fibonacci(20)), it's cacheFunction(Fibonacci)(20). You indeed cannot get the parameters of Fibonacci, you cannot alter that function to somehow access them. What cacheFunction is supposed to do is to construct a new function that provides the same functionality as the passed-in funct (i.e. Fibonacci in your case) by wrapping around it. In the wrapper function that will eventually get called with the input (e.g. 20) you can access the arguments and check the cache for their values, and potentially pass them on to funct.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-2

Memoization/caching technique is available as part of underscore.js. You can directly use it if needed. I also added a sitepoint article which walks you through implementing memoization in JS.

Implementing Memoization in JavaScript

memoize in underscorejs

Ravindran
  • 82
  • 1
  • 3