Today's Question:  What does your personal desk look like?        GIVE A SHOUT

How to write a function that takes a binary function, and makes it callable with two invocations in JavaScript?

This question is from Douglas Crockford. He askes the students to write a function that takes a binary function, and makes it callable with two invocations. Like : applyf(mul)(5)(6) == 30. Do you know how to write this function?

1 ANSWER



1

From Douglas Crockford, one solution is :

function applyf(binary){

return function(x){

return function(y){

return binary(x,y);

};

};

}

But this function is a bit tedious. Not very flexvible. One other method we can use is :

function applyf(){
    var that=arguments.callee,args=Array.prototype.slice.call(arguments);
    if(args.length==3){
        return (args[0])(args[1],args[2]);
    }else{
        return function(){
            return that.apply(this,args.concat(Array.prototype.slice.call(arguments)));
        };
    }
}

Here the variable that is the function applyf it self. args is an arguments array, in JavaScript, arguments is an internal variable of a function, it is an object, not an array, but arr array like object. So we cannot directly use arguments.slice() to return an array since it doesn't have a method called slice. Instead we use the Array.prototy.slice.call() method and pass the arguments as the this object, since arguments has a property length, the slice method can handle this object and return a new array.

Later we just need to check the number of args, if it's 3, then we execute the binary function and return the result. Otherwise, we continue to read arguments and execute the applyf function.

  REPLY  Posted by at 2013-02-25 22:42:58

POST ANSWER


Sorry! You need to login first to post answer.

OR

Login with Facebook Login with Twitter


Back to top