composing function adding new parameter

Viewed 69

I'm currently learning JavaScript and got stuck by adding a parameter to my function that should add two numbers. I'm not new to programming. Did a lot in Java and C#, but Javascript drives me crazy with scope and compose and currying.... So here is my problem:

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

The code above works! But i want that the +1 and +5 number to be variable so that i can have like this:

// Something linke this 
const compose = (f, g) => (a,b) => f(g(a,b));
const add1 = (num, num2) => num + num2;
const add5 = (num, num2) => num + num2;
compose(add1, add5)(10, 4)   // Those numbers should be the Parameter input for add1 and add5 (num, num2) 
2 Answers

Maybe like this:

    const addN = (n) => num => num + n
    const compose = (f,g) => a => f(g(a));
    const result = compose(addN(10),addN(4))(1);
    console.log(result);

addN creates adder functions, in this case an add10 and an add4. Instead of returning a value as your original add1 and add5 did, addN is returning a function like add1 and add5 except it isn't hardcoded to be +1 or +5; it is + whatever you passed in when you called addN.

console.log(addN(6)(10)); //16

addN(6) creates an "add6" function, and then we call that "add6" function with 10 to get the output of 16

You can also use curried function like this to achieve the same in a better / simpler way without composing it.

// add = a => b => Number
const add = a => b => a + b;

const result = add(2)(3); // => 5

First, the function takes a, and then returns a new function, which then takes b returns the sum of a and b. Each argument is taken one at a time. If the function had more parameters, it could simply continue to return new functions until all of the arguments are supplied and the application can be completed.

Related