OdeToCode IC Logo

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