Make the JavaScript Test Pass

Thursday, June 17, 2010

Add code on the commented line:

var f = function () {       
    var value = // ???
    return f.sum = (f.sum || 0) + value;
}

... to make the following QUnit test pass:

test("Running sum", function () {

    equals(f(3), 3);
    equals(f(3), 6);
    equals(f(4), 10);

    jQuery([1, 2, 3]).each(f);
    equals(f(0), 16);

});

Possible Answer

It's a goofy scenario, but one possible solution uses a technique you'll see frequently inside today's JavaScript libraries. First, we'll need to use the implicit arguments parameter inside the function f, and take (pop) just the last value. This would be trivially easy if the arguments parameter was an array, but arguments doesn't have any of the Array methods like pop, push, and slice. However, we can still use Array's pop method like this:

var value = Array().pop.call(arguments);

... or ...

var value = Array.prototype.pop.call(arguments);

... or ...

var value = [].pop.call(arguments);

Comments
gravatar Doeke Saturday, July 10, 2010
In your unit test, the last argument in the call to f is always the first argument.

So why not use:
var value = arguments[0];

or if you want the last one:
var value = arguments[arguments.length-1];
gravatar scott Saturday, July 10, 2010
@Doeke - right - I was just showing one possible solution (because it's a piece of code you might run across in some js libraries).
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!