Reputation: 524
I got stuck at a problem in JavaScript which uses the concept of function scope. Particularly, this is what I need to solve:
Define a function named callFunc that takes one argument, a function f. It should return an array containing the values f(0), f(0), f(1), f(1). You can only call f twice.
My code so far is:
var f = function(x) {
return x+2;
};
var callFunc = function (f) {
return [f(0), f(1)];
};
I don't know how I can return an array of four elements using only two calls and the JavaScript function scope principles.
Upvotes: 3
Views: 220
Reputation: 324620
It's really quite simple:
function callFunc(f) {
var f0, f1;
f0 = f(0);
f1 = f(1);
return [f0,f0,f1,f1];
}
I'm... not entirely sure why you'd have trouble with that. Reducing the number of function calls is something you should be doing anyway (and it's why I cringe at most jQuery code that has $(this)
in it like 20 times...)
Upvotes: 6