Skip to content

Commit 642b39d

Browse files
committed
Lesson 25 rename and add comments
1 parent 27348ff commit 642b39d

File tree

2 files changed

+96
-82
lines changed

2 files changed

+96
-82
lines changed
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
const { Box, Either, Right, Left, fromNullable } = require('../examples/lib')
2+
3+
const { List } = require('immutable-ext')
4+
5+
const Task = require('data.task')
6+
7+
// 'chain' does not exist on the array,
8+
// so we apply natural transformation into the List first
9+
const res = List(['hello', 'world'])
10+
.chain( x => List(x.split('')) )
11+
12+
console.log(res)
13+
14+
15+
// natural tranformation from array to Either
16+
// safe first element
17+
const first = xs =>
18+
fromNullable(xs[0])
19+
20+
21+
const largeNumbers = xs =>
22+
xs.filter( x => x > 100 )
23+
24+
const larger = x =>
25+
x * 2
26+
27+
28+
const app = xs =>
29+
30+
// map, then first
31+
first(
32+
largeNumbers(xs)
33+
.map(larger)
34+
)
35+
36+
console.log(app([2, 400, 5, 1000]))
37+
38+
const app1 = xs =>
39+
40+
// first, then map
41+
first(
42+
largeNumbers(xs)
43+
)
44+
.map(larger)
45+
46+
console.log(app1([2, 400, 5, 1000]))
47+
48+
49+
// fake user returned by id for testing purposes
50+
const fake = id => ({
51+
id: id,
52+
name: 'user1',
53+
best_friend_id: id + 1
54+
})
55+
56+
const Db = ({
57+
find: id => new Task(
58+
(rej, res) =>
59+
// simulate error 'not found' for id <= 2
60+
res( id > 2 ? Right(fake(id)) : Left(fake('not found')) )
61+
)
62+
})
63+
64+
// natural transform Either to Task
65+
const eitherToTask = e =>
66+
e.fold(Task.rejected, Task.of)
67+
68+
69+
// valid user (id > 2)
70+
// -> Task returns Either
71+
Db.find(3)
72+
73+
// Task result is 'Either' but we want to chain with plain function,
74+
// so apply natural transformation Either to Task first,
75+
.chain(eitherToTask)
76+
77+
// now we have Task returning plain value,
78+
// errors were already sent to Task.rejected,
79+
// now map the result into another Task
80+
.chain(user => Db.find(user.best_friend_id))
81+
82+
// the new result is again an Either,
83+
// so we map it again from Either to Task
84+
.chain(eitherToTask)
85+
.fork(console.error, console.log)
86+
87+
88+
// invalid user (id = 2)
89+
Db.find(2)
90+
.chain(eitherToTask)
91+
.chain(user => Db.find(user.best_friend_id))
92+
.chain(eitherToTask)
93+
.fork(console.error, console.log)
94+
95+
96+

examples/apply-natural-transformations.js

Lines changed: 0 additions & 82 deletions
This file was deleted.

0 commit comments

Comments
 (0)