Create a Function with Appended Partials in JavaScript
In JavaScript, partial functions let you predefine some arguments of another function and call it later with remaining ones, making code cleaner and reusable.
- Partial application predefines some arguments of a function for later use.
- Uses the spread (
...) operator to handle fixed and dynamic arguments. - Helps create reusable and simplified versions of complex functions.
[Approach 1]: Using the Spread Operator to Append Partials
We want to implement a function that invokes another function and provides the arguments it received.
- We can get the result by using (...) the spread operator.
- Create a main function (
math) that passes received arguments to another function. - The first argument is the target function name; the rest (
...params) are its parameters. - Use the spread operator (
...params) to call the target function with those arguments. - Define helper functions like
sum,sub,mul, andpowto perform operations using the passed arguments.
// Function "math" responsible for
// passing the arguments
const math = (functionName,
...params) => functionName(...params);
//function to add all passed arguments
const sum = (...args) => {
var result = 0;
for (const val of args) {
result += val;
}
console.log(result);
}
// Function to subtract all
// passed arguments
const sub = (...args) => {
var result = 0;
for (const val of args) {
result -= val;
}
console.log(result);
}
// Function to multiply all
// passed arguments
const mul = (...args) => {
var result = 0;
for (const val of args) {
result *= val;
}
console.log(result);
}
// Call to the functions via "math"
math(sum, 2, 3, 4, 5, 6);
math(sub, 5, 4, 1);
math(mul, 2, 3, 5, 6);
Output: The math function has successfully called the other functions and appended the required arguments.
20
-10
0[Approach 2]: Using Rest Parameters for Partial Application
- following example demonstrates a function that uses the first two arguments.
- It has used the first two arguments and our "args" is referring to the rest of the arguments leaving the first two arguments.
const fun = (arg1, arg2, ...args) => {
console.log(args);
}
fun(1, 2, 3, 4, 5, 6);
Output:
[ 3, 4, 5, 6 ]