Functions Compose

    Feb 21, 2023

    Definitions and examples for Functions Compose

    The function compose borrowed thinking from pipeline in Unix-Shell Programming with taking out of a function's output as other function's input.

    For example,

    # The content of test.txt is 'Hello'
    cat test.text | grep 'World'
    # Output : Hello World
    

    At above example the symbol | is treated as pipeline operator, it transfer the left output to right input.

    So the compose in Functional Programming is simply defined as following implement in javascript

    const compose = (funa, funb) => (c) => funa(funb(c));
    

    The compose function accepts two functions as arguments and returns new function that accepts an initial input and applys functions one by one.

    In fact the above definition has same effects with

    const temp = funb(data);
    const result = funa(temp);
    

    Bear in mind that the order of function calls is inside out and appears in compose function is from right to left.

    We also have expansion definition for multiple functions compose

    const composeN =
      (...funcs) =>
      (data) =>
        reduce(funcs.reverse(), (acc, fn) => fn(acc), value);