Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compose javascript functions with more than one argument

How can I convert this function composition into more readable format?

funcA(argumentA, funcB(argumentA, funcC(argumentA, argumentB)))

What I'd like to achieve is something more like this:

compose(funcC, funcB, funcA)(argumentA, argumentB)

I'm using this compose function implementation:

const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)))

The problem is I need argumentA in all function calls as a first parameter and every function returns a value to be passed as a second parameter to the next function. I know I could create separate function-returning functions and use them like so:

compose(funcCWithArg(argumentA), funcBWithArg(argumentA), funcAWithArg(argumentA))(argumentB)

but in my actual case there aren't only three of them, but many more and that would require some serious amount of code just to write them down. Is there a simpler way to do that?

EDIT: I can't use any external library. Only vanilla js.

like image 501
zorza Avatar asked Jun 19 '17 08:06

zorza


People also ask

Can you write functions that accept multiple arguments?

Functions can accept more than one argument. When calling a function, you're able to pass multiple arguments to the function; each argument gets stored in a separate parameter and used as a discrete variable within the function.

How can I pass multiple parameters in JavaScript function?

When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit. In the above function, if we pass any number of arguments, the result is always the same because it will take the first two parameters only.

Which function accepts two arguments in JavaScript?

Let's start by creating a function called add that can accept 2 arguments and that returns their sum. We can use Node. js to run the code node add_2_numbers.

How many arguments can you use in custom functions?

We will use the simple example of conversion of meters to feet again to illustrate how two arguments can be fed to a function. You can apply as many arguments as you wish to a function.


1 Answers

Using vanilla JS,

const compose = (...fns) => (arg1, arg2) => fns.reduce((arg, f) => f(arg1, arg), arg2);

Explanation

compose becomes a function returning a function, which loops through the list of functions passed to it, passing the first argument to every function call.

Test

const sum = (a, b) => (a + b);
const mult = (a, b) => (a * b);
compose(sum, mult)(2, 3) === mult(2, sum(2, 3));  // true
like image 145
Chitharanjan Das Avatar answered Oct 01 '22 22:10

Chitharanjan Das