Skip to content

Instantly share code, notes, and snippets.

@Charlyzzz
Created May 13, 2020 13:34
Show Gist options
  • Save Charlyzzz/75ea94562740d3eb9ed54ebaa0e26eab to your computer and use it in GitHub Desktop.
Save Charlyzzz/75ea94562740d3eb9ed54ebaa0e26eab to your computer and use it in GitHub Desktop.
export function compose(...functions) {
if (functions.length === 0) {
throw new Error("No functions to compose!");
}
return (v) => {
return functions.reduceRight((value, newFunction) => newFunction(value), v);
};
}
import { compose } from "./compose";
test("fails without fns", () => {
expect(() => compose()).toThrowError("No functions to compose!");
});
test("single fn compose behaves like the same fn", () => {
const add2 = (n) => n + 2;
expect(compose(add2)(2)).toEqual(4);
});
test("applies functions from right to left", () => {
const add2 = (n) => n + 2;
const divideBy2 = (n) => n / 2;
expect(compose(divideBy2, add2)(4)).toEqual(3);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment