There is a method bind available in function.prototype
of JavaScript. Do you know? May be.
I got to know about this in detail at quite a later time in my programming carrier. I heard and read about the method. But couldn’t find good example/use-case to use. Recently one of my colleagues came with a puzzle question, how to write this multiply
function so that the following would return 120
the product of the numbers passed.
multiply(1)(2)(3)(4)(5); |
He showed the solution as following:
function multiply (a) { |
But, somehow I didn’t like the solution. As we can multiply that many numbers equal to the number of funcitons returned in chained fashion. And thought that partial function can be a resort to solve this problem. So my solution was:
'use strict'; |
But here we only have to call this as multiply(2)(3)(4)(5)(6)(7)()
, with an extra parenthesis to call the last generated function. Also, we have to be careful about the sentinel constraint as described in the comment.
Until the last call of the method, it actually returns partial functions. And for the first and last case, we are relying on the fact, that this
would be undefined
in the first case and in the last call (the sentinel call), b
would be undefined
as well as this
would be null
not undefined
.
It’s a good use-case to use bind
. And with this implementation we are not restricting ourselves to the number of operands, can be passed.