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.

2
  • 1
    Maybe you should tell us what language you are using. Commented May 19, 2015 at 4:36
  • Totally ! it's in javaScript Commented May 19, 2015 at 4:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Works until the calculation yields "hasOwnProperty":-) +1 nonetheless.
@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), but sometimes forget.
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));

1 Comment

Thanks! It is _.memoize indeed, but I'm working on the implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.