Search code examples
javascriptfunctional-programmingcompositioncurrying

Are 'currying' and 'composition' the same concept in Javascript?


Recently I read about function composition in a Javascript book, and then on a website I saw someone reference it as currying.

Are they the same concept?


Solution

  • @Omarjmh's answer is good but the compose example is overwhelmingly complex for a learner, in my opinion

    Are they the same concept?

    No.

    First, currying is translating a function that takes multiple arguments into a sequence of functions, each accepting one argument.

    // not curried
    const add = (x,y) => x + y;
    add(2,3); // => 5
    
    // curried
    const add = x => y => x + y;
    add(2)(3); // => 5
    

    Notice the distinct way in which a curried function is applied, one argument at a time.


    Second, function composition is the combination of two functions into one, that when applied, returns the result of the chained functions.

    const compose = f => g => x => f(g(x));
    
    compose (x => x * 4) (x => x + 3) (2);
    // (2 + 3) * 4
    // => 20
    

    The two concepts are closely related as they play well with one another. Generic function composition works with unary functions (functions that take one argument) and curried functions also only accept one argument (per application).

    // curried add function
    const add = x => y => y + x;
    
    // curried multiplication function
    const mult = x => y => y * x;
    
    // create a composition
    // notice we only apply 2 of comp's 3 parameters
    // notice we only apply 1 of mult's 2 parameters
    // notice we only apply 1 of add's 2 parameters
    let add10ThenMultiplyBy3 = compose (mult(3)) (add(10));
    
    // apply the composition to 4
    add10ThenMultiplyBy3(4); //=> 42
    
    // apply the composition to 5
    add10ThenMultiplyBy3(5); //=> 45