Created
May 13, 2020 13:34
-
-
Save Charlyzzz/75ea94562740d3eb9ed54ebaa0e26eab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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