Skip to content

Commit

Permalink
feat(ch12): add Monad example
Browse files Browse the repository at this point in the history
  • Loading branch information
poulzinho committed Feb 16, 2020
1 parent 1d5f42c commit f977e00
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions src/ch-12_monads/12.1_monads.test.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,42 @@
import {assert, expect} from 'chai';
import {expect} from 'chai';
import {flatMap} from "./12.1_monads";

describe("Monads", () => {
it("should enable flatMap", () => {
const echo = n => x => Array.from({length: n}).fill(x);

expect(flatMap(echo(2), [1, 2, 3])).deep.equal([1, 1, 2, 2, 3, 3]);
})
});

it("should implement a Monad", () => {
const Monad = value => ({
flatMap: f => {
console.log('** flatMap');
console.log('-- f', f.toString());
console.log('-- value', value);
return f(value)
},
map(f) {
console.log('* map');
console.log('- f', f.toString());
console.log('- value', value);

return this.flatMap(a => {
console.log('exec flatMap f');
console.log('--- f', f.toString());
console.log('--- a', a);
console.log('--- f(a)', f(a));
console.log('--- Monad.of', Monad.of(f(a)));
return Monad.of(f(a))
});
}
});

Monad.of = x => {
console.log('*** Monad(x)', x);
return Monad(x)
};

expect(Monad(21).map(x => x * 2).flatMap(x => x)).equal(42);
});
});

0 comments on commit f977e00

Please sign in to comment.