Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript function scope challenge

Tags:

javascript

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.

like image 478
Radu Avatar asked Dec 13 '25 17:12

Radu


1 Answers

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...)

like image 140
Niet the Dark Absol Avatar answered Dec 15 '25 08:12

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!