Johann Davel De Beer
Johann Davel De Beer

Reputation: 51

Difficulty understanding Javascript composing in this function

Im following this course and came across this problem

const compose = (f, g) => (a) => f(g(a));
const add1 = (num) => num + 1;
const add5 = (num) => num + 5;
compose(add1, add5)(10)

As i understand it g(a) gets run first so num = 1 makes 1 for g and 10 for a, that makes it f(1(10)). But how does the 1 and the 10 know to add, why doesn't it multiply or minus ?

Upvotes: 1

Views: 114

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36594

that makes it f(1(10))

This is not true. Because 1(10) is not even a valid javascript syntax. When the value 10 is passed to the function g its returns five more than the value which is 15. This is because its defined in the function add5 which is passed as g to the compose function

The value returned from the above function call which is 15 is then passed to f which is add1. So in the last it returns 16

But how does the 1 and the 10 know to add, why doesn't it multiply or minus.

You are using + inside the functions passed. If you will use - or * it will then multiply or minus

Upvotes: 4

username-yj
username-yj

Reputation: 101

This is a technique known as currying.

Your compose function takes two functions as arguments.

Those functions each take a single num argument.

When you call compose(add1, add5)(10) the expression is parsed as the following:

Give me the output of calling add1 on the output of calling add5(10). In Javascript syntax, this looks like, f(g(a)), i.e. add1(add5(10)).

If you follow and evaluate the expressions in order, it goes:

compose(f, g)(a) === f(g(a))

compose(add1, add5)(10) === add1(add5(10)) === add1(15) === 16

Upvotes: -1

Related Questions