0

I was just wondering if there was a way to extract the arguments of a function x(...){...} to the global scope and maybe store them into a variable.

I know that if you construct a function, you can return the "arguments" object, but that is not what I want because the function is unknown.

To give a bit of context as of why I want to do this, I'm trying to create a function "a" that receives a function "x" as a parameter, and I need to return a function "y" that, when called, will check if it has already computed the result for the given argument and return that value instead if possible.

I'm aware that this is probably not the best approach to get it done.

Andres C. Viesca
  • 332
  • 5
  • 19

2 Answers2

1

The term for what you're trying to do is "memoization" and it doesn't require exporting arguments to the global scope.

If you use Lodash/Underscore, it has a built in function for this:

var calculate = function (num) {
    console.log('I have been called!');
    ...
};

calculate = _.memoize(calculate);

console.log(calculate(4));
console.log(calculate(5));
console.log(calculate(4));
JLRishe
  • 99,490
  • 19
  • 131
  • 169
1

I'm guessing a little bit as to what exactly you want to do, but here's a structural idea. This creates a function that caches its results so for a given input argument, the result is only ever calculated once (and then retrieved from the cache after that). It assumes that the argument to the function is a string or anything else that has a unique toString() conversion.

var myFunc = (function() {
     var cache = {}, has = Object.prototype.hasOwnProperty;
     return function(arg) {
         if (has.call(cache, arg)) {
             return cache[arg];
         } else {
             // do your calculation on arg to generate result
             // ...
             cache[arg] = result;
             return result;
         }
     }
})();

This implementation is optimized for a function with a single argument, but if you wanted to cache based on multiple arguments, it could be extended for that too by constructing a unique key based on the combination of all the arguments and caching based on that key.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Works until the calculation yields `"hasOwnProperty"`:-) +1 nonetheless. – Bergi May 19 '15 at 04:54
  • @Bergi - OK, I fixed it so it will even work with `"hasOwnProperty"` as the arg. I have made it immune to that before (like in this [`Set` implementation](http://stackoverflow.com/questions/7958292/mimicking-sets-in-javascript/7958422#7958422)), but sometimes forget. – jfriend00 May 19 '15 at 04:56