In this article, we will learn to create a function that invokes a function with partials appended to the arguments it receives in JavaScript.
Approach: 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/rest operator.
Explanation: Let’s say, we create one function math that will be responsible for passing the arguments. We separate out our arguments for the math function. The first argument is reserved for the functionName and by giving “. . .params”, it will refer to other arguments as parameters for the functionName. We call the functionName and pass the rest of the arguments using “. . . params”.
In the following code, math takes many arguments. It reserves the first argument as the function name and the rest of the arguments as its parameters.
We can define different functions which will get their arguments from the math function. We have defined function sum which takes all the arguments and make it an array by taking them as (. . . args), and iterating through them to perform the task. Similarly, other functions like sub, mul, pow are implemented.
Example 1: This example shows the above-explained approach.
Javascript
<script> // 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); </script> |
Output: The math function has successfully called the other functions and appended the required arguments.
20 -10 0
Example 2: The 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.
Javascript
<script> const fun = (arg1, arg2, ...args) => { console.log(args); } fun(1, 2, 3, 4, 5, 6); </script> |
Output:
[ 3, 4, 5, 6 ]