After reading your post,
I was playing around to implement it with Function#bind but it seems like it's not possible to know when user is "done" with arguments and calculate the "add" without knowing the "arity" (parameter count).
I ended up using "done" as an end condition but one can probably specify the arity initially as a second argument of curriedAdd(arity, value) and compare the arity against the argument length.
But then at this point, it will be a partial application, not a currying...
And then I was surprised 😮 to learn from your post that the type-coercion using + causes .valueOf to be called.
.
So I've tried for the 3rd time to make the function work as yours do using .valueOf.
This post got me really thinking about currying and steps to reach your conclusion as well as mine.
Below is the source above.
functioncurriedAdd(v1){if(arguments[arguments.length-1]==="done"){console.log(`done...`)returnArray.prototype.slice.apply(arguments,[0,arguments.length-1]).reduce((acc,v)=>acc+=v)};console.log(`v1`,v1,`arguments`,...arguments,'arg.length',arguments.length)returncurriedAdd.bind(null,...arguments);}functioncurriedAdd2(arity,v1){// "-1" to account for the arityif(arguments.length-1===arity){returnArray.prototype.slice.call(arguments,1).reduce((acc,v)=>acc+=v,0)};returncurriedAdd2.bind(null,...arguments);}functioncurriedAdd3(){constinner=curriedAdd3.bind(null,...arguments)inner.valueOf=()=>[...arguments].reduce((acc,v)=>acc+=v,0);returninner;}
Wow, thanks for the such detailed comment! I did not think about binding and collecting arguments with each function call. JS is so flexible language that allows many ways to solve a problem. Thanks for sharing your path!
Thanks for the fun post Eugene.
After reading your post,
I was playing around to implement it with Function#bind but it seems like it's not possible to know when user is "done" with arguments and calculate the "add" without knowing the "arity" (parameter count).
I ended up using "done" as an end condition but one can probably specify the arity initially as a second argument of
curriedAdd(arity, value)
and compare the arity against the argument length.But then at this point, it will be a partial application, not a currying...
And then I was surprised 😮 to learn from your post that the type-coercion using
+
causes.valueOf
to be called..
So I've tried for the 3rd time to make the function work as yours do using
.valueOf
.This post got me really thinking about currying and steps to reach your conclusion as well as mine.
Below is the source above.
Wow, thanks for the such detailed comment! I did not think about
bind
ing and collecting arguments with each function call. JS is so flexible language that allows many ways to solve a problem. Thanks for sharing your path!I found your approach your readable as it is more intentional what the code is doing 🙂