Skip to content

Commit

Permalink
feat(ch10): compose functions with a reducerRight
Browse files Browse the repository at this point in the history
  • Loading branch information
poulzinho committed Jan 25, 2020
1 parent 7878c64 commit 686e507
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {expect} from 'chai';
import {add, addN, filterRed, map, mapRedu} from "./10.1_abstraction_and_composition";
import {add, addN, compose, filterRed, map, mapRedu} from "./10.1_abstraction_and_composition";

describe("Abstraction and Composition", () => {
it("should fix a parameter in a function", () => {
Expand Down Expand Up @@ -47,4 +47,14 @@ describe("Abstraction and Composition", () => {
expect(filterRed(gt5, terms)).to.deep.equal([6, 10]);
});

it("should compose functions using a right to left reducer", () => {
const add1 = x => x + 1;
const add5 = x => x + 5;
const multiplyWith3 = x => x * 3;

const composedFn = compose(add1, add5, multiplyWith3);

expect(composedFn(5)).to.equal(21);
});

});
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ export const mapRedu = (fn, arr) => arr.reduce((acc, item) => {
export const filterRed = (fn, arr) => arr.reduce((acc, item) => {
return fn(item) ? acc.concat([item]) : acc;
}, []);

export const compose = (...fns) => x => fns.reduceRight((y, f) => f(y), x);

0 comments on commit 686e507

Please sign in to comment.