I am new to functional programming paradigms in JavaScript and trying to learn about partial application in JavaScript.
One exercise that I am working through is a problem that is supposed to be simple - a 3-way sum that is supposed to give the same answers for the following:
partialThreeSum()(a, b, c) === partialThreeSum(a, b)(c) === partialThreeSum(a, b, c) === partialThreeSum(a)(b, c)
'use strict';
function partialThreeSum(a, b, c):
const threeSum = (a, b, c) => a + b + c;
return partial(threeSum, a, b, c);
I am having trouble implementing the partial method to allow partial application and return the function with only certain arguments applied. I have looked at the following approaches, all to no avail:
- Implement
const partial
const partial = (fn, ...fixedArgs) => (...remainingArgs) => fn(...fixedArgs, ...remainingArgs);
- Enable partial application
const enablePartialApplication = (fn) => (...args) => {
if (args.length >= fn.length) return fn(...args);
return enablePartialApplication(fn.bind(null, ...args));
};
function partialThreeSum(a, b, c) {
return enablePartialApplication((a, b, c) => a + b + c);
}
source: https://dev.to/ycmjason/how-to-make-functions-partially-applicable-in-javascript--416b
this doesn't really work since sometimes an Anonymous function is returned. Also, I know ahead of time how many arguments the function should take (namely, 3), so I believe there should be a simpler way to implement such that the results of partial application
partialThreeSum()(a, b, c)
partialThreeSum(a, b, c)
partialThreeSum(a, b)(c)
partialThreeSum(a)(b, c)
What is a proper way to implement this for a given number of arguments? I am trying to implement this without any outside libraries (such as lodash) and I am doing use strict, so I cannot use caller, callee, arguments properties. (as shown in https://ada.adrianheine.de/partial-application-js)
Other sources on the internet suggest similar methods, but there is no solution that I can see that can be simply applied to this problem. I am looking to see if there might be an elegant way to accomplish this.