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.
Indexing |
| By sonic0002 |
RECENT
- ► GPT-5 solved the math problems on ErdosProblems.com by merely finding existing answers online, not developing new algorithms
- ► Does your company allow code agent such as Cursor?
- ► What do we do if a workaholic superstar joins our department?
- ► What tech related movies or shows have you watched?
- ► What bad comments do people have on GoLang?
- ► Are you using Cursor or Windsurf?
- ► Will AI Replace Programmers?
- ► What Is Your AI Learning Story?
- ► What Chrome extensions do you find useful for programmers?
- ► What does your personal desk look like?