-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5eitherexample.js
More file actions
49 lines (43 loc) · 887 Bytes
/
5eitherexample.js
File metadata and controls
49 lines (43 loc) · 887 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// const Either = Left | Right
const Right = x =>
({
chain: f => f(x),
map: f => Right(f(x)),
inspect: () => `Right(${x})`,
fold: (f,g) => g(x)
})
const Left = x =>
({
chain: f => Left(x),
map: f => Left(x),
inspect: () => `Left(${x})`,
fold: (f,g) => f(x)
})
const fromNullable = x =>
x !=null ? Right(x) : Left(x)
const fs = require('fs');
const getPort = () => {
try {
const str = fs.readFileSync('confg.json');
const config = JSON.parse(str)
return config.port;
} catch(e) {
return 3000
}
}
const result = getPort()
// console.log(result)
//functional way
const tryCatch = (x) => {
try {
return Right(x)
} catch(e) {
return Left(e)
}
}
const getPortFunctional = () =>
tryCatch(() => fs.readFileSync('config.json'))
.chain(c => tryCatch(() => JSON.parse(c)))
.fold(e => 3000,
c => c.port)
console.log(getPortFunctional())