Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Last active May 17, 2022 17:38
Show Gist options
  • Save JamieMason/172460a36a0eaef24233e6edb2706f83 to your computer and use it in GitHub Desktop.
Save JamieMason/172460a36a0eaef24233e6edb2706f83 to your computer and use it in GitHub Desktop.
ES6 JavaScript compose function

ES6 JavaScript Compose Function

Definition

const compose = (...fns) =>
  fns.reduceRight((prevFn, nextFn) =>
    (...args) => nextFn(prevFn(...args)),
    value => value
  );

Example

Create the function, composed of three others:

const example = compose(
  val => { console.log(1); return `1<${val}>`; },
  val => { console.log(2); return `2<${val}>`; },
  val => { console.log(3); return `3<${val}>`; }
);

Call the function:

example('hello')

Console output is:

3
2
1
"1<2<3<hello>>>"
@noel-yap
Copy link

Similar to @parkerault, I have (in TypeScript):

export module Functions {
  export function compose(...fns: ((...any) => any)[]): any {
    return (...args: any[]) => {
      return fns.reduceRight((arg: any, f: (...any) => any) => {
        return (Array.isArray(arg)) ? f(...arg) : f(arg);
      }, args);
    };
  }
}

which passes the Ava test:

test('compose should compose', t => {
  const g = (x, y) => x + y;
  const f = n => n * 2;

  const h = Functions.compose(f, g);

  t.is(42, h(19, 2));
});

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