Skip to content

Instantly share code, notes, and snippets.

@daniil4udo
Created June 8, 2019 22:31
Show Gist options
  • Save daniil4udo/44db69a443ddd241aaa6227f5011c65e to your computer and use it in GitHub Desktop.
Save daniil4udo/44db69a443ddd241aaa6227f5011c65e to your computer and use it in GitHub Desktop.
Compose & Pipe functions in JavaScript

Compose functions in JavaScript

Order - right to left


//compose for multiple functions
const composeMultiple = (f, g) => (...data) => f(g(...data)) //composing 2 functions
const composeFunctions = (...fns) => fns.reduce(composeMultiple)

//or one line
compose = (...fns) => value => fns.reduceRight((v, f) => f(v), value);

Pipe functions in Javascript

Order - left to right


//pipe multiple functions
const pipeMultiple = (f, g) => (...data) => g(f(...data)) //composing 2 functions
const pipeFunctions = (...fns) => fns.reduce(pipeMultiple)

//or one line
pipe = (...fns) => value => fns.reduce((v, f) => f(v), value)

//
pipeDebug = (...functions) => (value) => {
    debugger;
    return functions
        .reduce((currentValue, currentFunction) => {
            debugger;
            return currentFunction(currentValue);
        }, value)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment