-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplayground.js
58 lines (46 loc) · 1.38 KB
/
playground.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
const fs = require('fs')
const Box = require('./box')
const { Left, Right, fromNullable } = require('./either')
const nextCharFromNumberString = str =>
Box(str)
.map(s => s.trim())
.map(parseInt)
.map(i => i + 1)
.map(String.fromCharCode)
.fold(c => c.toLowerCase())
console.log(nextCharFromNumberString(' 64 ')) // a
const moneyToFloat = str =>
Box(str)
.map(s => s.replace(/€/g, ''))
.map(parseFloat)
const percentToFloat = str =>
Box(str)
.map(s => s.replace(/%/g, ''))
.map(parseFloat)
.map(n => n * 0.01)
const applyDiscount = (price, discount) =>
moneyToFloat(price).fold(cost =>
percentToFloat(discount).fold(savings => cost - cost * savings)
)
console.log(applyDiscount('5.00€', '20%')) // 4 (€)
const findColor = name =>
fromNullable({ red: '#f00', green: '#0f0', blue: '#00f' }[name])
const returnHexColor = n =>
findColor(n)
.map(c => c.slice(1))
.fold(_ => 'COLOR NOT FOUND', c => c.toUpperCase())
console.log(returnHexColor('blue')) // 00F
console.log(returnHexColor('yellow')) // COLOR NOT FOUND
const tryCatch = f => {
try {
return Right(f())
} catch (e) {
return Left(e)
}
}
const getPort = file =>
tryCatch(() => fs.readFileSync(file))
.chain(c => tryCatch(() => JSON.parse(c)))
.fold(_ => 3000, c => c.port)
console.log(getPort('config.json')) // 8080
console.log(getPort()) // 3000