|
1 | 1 | 'use strict'; |
2 | 2 |
|
3 | | -const fp = {}; |
4 | | - |
5 | | -fp.mapNull = (fn, x) => (x ? fn(x) : null); |
6 | | - |
7 | | -fp.maybe = x => { |
8 | | - const map = fn => fp.maybe(fp.mapNull(fn, x)); |
9 | | - map.ap = fnA => fnA(fn => fp.mapNull(fn, x)); |
10 | | - map.chain = fnM => fnM(x); |
11 | | - return map; |
| 3 | +const maybe = x => { |
| 4 | + const map = fn => maybe(x ? fn(x) : null); |
| 5 | + const ap = functor => functor.map(f => x && f ? f(x) : null); |
| 6 | + const chain = f => f(x); |
| 7 | + return Object.assign(map, { map, ap, chain }); |
12 | 8 | }; |
13 | 9 |
|
14 | 10 | // Usage |
15 | 11 |
|
16 | | -fp.maybe(5)(x => x * 2)(x => ++x)(console.log); |
17 | | -fp.maybe(5)(x => x * 2).ap(fp.maybe(x => ++x))(console.log); |
18 | | -fp.maybe(5).chain(x => fp.maybe(x * 2))(x => ++x)(console.log); |
19 | | - |
20 | | -const config = { |
21 | | - coords: { |
22 | | - x: 0, |
23 | | - y: 5, |
24 | | - }, |
25 | | - velocity: { |
26 | | - x: 1, |
27 | | - y: 1, |
28 | | - }, |
29 | | -}; |
30 | | - |
31 | | -const addVelocity = velocity => coords => { |
32 | | - coords.x += velocity.x; |
33 | | - coords.y += velocity.y; |
34 | | - return coords; |
35 | | -}; |
| 12 | +const twice = x => x * 2; |
| 13 | +const inc = x => ++x; |
36 | 14 |
|
37 | | -const coords = fp.maybe(config.coords); |
38 | | -const velocity = fp.maybe(config.velocity); |
39 | | -coords.ap(velocity(addVelocity))(console.log); |
| 15 | +maybe(5)(twice)(inc)(console.log); |
| 16 | +maybe(5).map(twice).map(inc).map(console.log); |
| 17 | +maybe(5)(twice).ap(maybe(inc))(console.log); |
| 18 | +maybe(5)(twice).ap(maybe())(console.log); |
| 19 | +maybe(5).chain(x => maybe(x * 2))(inc)(console.log); |
| 20 | +maybe(5).chain(x => maybe(x * 2)).map(inc)(console.log); |
0 commit comments