@@ -3,30 +3,46 @@ const { Box, Either, Right, Left, fromNullable } = require('../examples/lib')
3
3
const Task = require ( 'data.task' )
4
4
5
5
6
+ const eitherToTask = e =>
7
+ e . fold ( Task . rejected , Task . of )
6
8
9
+ eitherToTask ( Right ( 'nightingale' ) )
10
+ . fork (
11
+ e => console . error ( 'Error: ' , e ) ,
12
+ res => console . log ( 'Result: ' , res )
13
+ )
14
+ eitherToTask ( Left ( 'errrr' ) )
15
+ . fork (
16
+ e => console . error ( 'Error: ' , e ) ,
17
+ res => console . log ( 'Result: ' , res )
18
+ )
7
19
8
20
21
+ // naturally transform Box to Either
9
22
const boxToEither = b =>
10
23
11
24
// must go to Right
12
25
// to follow the natural transformation law
13
26
b . fold ( Right )
14
27
28
+ // first transform to Either, than map
15
29
const res1 = boxToEither ( Box ( 100 ) )
16
30
. map ( x => x * 2 )
17
31
18
- // first map, then transform
32
+ // or first map, then transform to Either
19
33
const res2 = boxToEither (
20
34
Box ( 100 ) . map ( x => x * 2 )
21
35
)
22
36
37
+ // results should be the same!
23
38
console . log ( res1 , res2 )
24
39
25
40
26
41
27
42
const boxToEitherBad = b =>
28
43
29
44
// does not follow the natural transformation law
45
+ // because Left ignores mapped functions
30
46
b . fold ( Left )
31
47
32
48
// first box, then map
@@ -42,7 +58,7 @@ const res22 = boxToEither(
42
58
console . log ( res21 , res22 )
43
59
44
60
45
-
61
+ // transform List into Either
46
62
const first = xs =>
47
63
fromNullable ( xs [ 0 ] )
48
64
0 commit comments