Question

I am trying to write a currying function in JavaScript,the inner function does not update the value of the array args:

var myCurry=function(fn)
{
    var len=fn.length;
    var _slice=Array.prototype.slice;
    var args=_slice.call(arguments,1);
    console.log(args.length);
    return function next()
    {
        var rem=_slice.call(arguments,0)
        args.concat(rem);
        console.log(args.length);
        if(len<=args.length)
            return fn.apply(null,args);
        else
            return next;
    }
}

I call it like this:

 var _sum=myCurry(sum,2);
 var res=_sum(2);
 var res2=res(3,4);
 console.log(res2);

This returns the function next at all times,presumably because the array is not updated.How do I fix this error to ensure that the function work?

Was it helpful?

Solution 2

Oops:

args.concat(rem);

Instead:

args = args.concat(rem);

concat() performs no in-place modifications. It returns a new Array

OTHER TIPS

It's because .concat() doesn't mutate the array. Use .push() instead if you want to mutate the original.

args.push.apply(args, rem);

Or if you didn't care if the original was replaced, just assign the return value from .concat()

args = args.concat(rem);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top