Skip to content

Commit 40527c7

Browse files
committed
Extract use case forom prev example
1 parent 33e8b73 commit 40527c7

File tree

2 files changed

+44
-32
lines changed

2 files changed

+44
-32
lines changed

JavaScript/6-closure-ap.js

+13-32
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,20 @@
11
'use strict';
22

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 });
128
};
139

1410
// Usage
1511

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;
3614

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);

JavaScript/7-use-case.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
'use strict';
2+
3+
const maybe = x => {
4+
const map = fn => maybe(x ? fn(x) : null);
5+
map.ap = functor => functor(f => x && f ? f(x) : null);
6+
return map;
7+
};
8+
9+
// Usage
10+
11+
const config = {
12+
coords: {
13+
x: 0,
14+
y: 5,
15+
},
16+
velocity: {
17+
x: 1,
18+
y: 1,
19+
},
20+
};
21+
22+
const addVelocity = velocity => coords => {
23+
coords.x += velocity.x;
24+
coords.y += velocity.y;
25+
return coords;
26+
};
27+
28+
const coords = maybe(config.coords);
29+
const velocity = maybe(config.velocity);
30+
31+
coords.ap(velocity(addVelocity))(console.log);

0 commit comments

Comments
 (0)