-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrefactoringUsingEitherMonad_14.js
64 lines (53 loc) · 1.24 KB
/
refactoringUsingEitherMonad_14.js
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// holo
// Definitions
import fs from 'fs'
// ====================
const Right = x =>
({
chain: f => f(x),
map: f => Right(f(x)),
fold: (f, g) => g(x),
inspect: `Right(${x})`
})
const Left = x =>
({
chain: f => Left(x),
map: f => Left(x),
fold: (f, g) => f(x),
inspect: `Left(${x})`
})
const fromNullable = x =>
x != null ? Right(x) : Left(null)
const tryCatch = f => {
try {
return Right(f())
}catch(e){
return Left(e)
}
}
const getPort_ = () => {
try {
const str = fs.readFileSync('config.json')
const config = JSON.parse(str)
return config.port
} catch(e) {
return 54000
}
}
const readFileSync = path =>
tryCatch(() => fs.readFileSync(path))
const getPort__ = () =>
readFileSync('config.json')
.map( content => JSON.parse(content))
.map(config => config.port)
.fold(() => 8080, x => x)
const parseJSON = contents =>
tryCatch(() => JSON.parse(contents))
// flattering either monad with chain
const getPort = () =>
readFileSync('config.json')
.chain( content => parseJSON(content))
.map(config => config.port)
.fold(() => 8080, x => x)
const res = getPort()
console.log(res)