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
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(){ 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. | |
POST ANSWER
Sorry! You need to login first to post answer.
OR
A day of an intern |
By sonic0002 |
RECENT
- ► What does your personal desk look like?
- ► Happy Chinese New Year for those who celebrate it
- ► How much time do you code every day?
- ► What lies would programmers like to tell?
- ► Is GoLang being used in more and more startups?
- ► How do you feel about 996?
- ► What are your reasons not writing blogs?
- ► Why do you or do not write tech blogs?
- ► What weekend projects have you created?
- ► What's your opinion about Alibaba mooncake incident?