-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctor-exercises.js
More file actions
49 lines (42 loc) · 1.22 KB
/
functor-exercises.js
File metadata and controls
49 lines (42 loc) · 1.22 KB
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
//source: https://codepen.io/drboolean/pen/poodxOm?editors=0010
const Box = (x) => ({
map: (f) => Box(f(x)),
fold: (f) => f(x),
toString: () => `Box(${x})`,
})
// Exercise: Box
// Goal: Refactor each example using Box
// Keep these tests passing!
// Bonus points: no curly braces
// Ex1: Using Box, refactor moneyToFloat to be unnested.
// =========================
const moneyToFloat = (str) =>
Box(str)
.map((str) => str.replace(/\$/, ""))
.fold(parseFloat)
// Ex2: Using Box, refactor percentToFloat to remove assignment
// =========================
const percentToFloat = (str) =>
Box(str.replace(/\%/, ""))
.map(parseFloat)
.fold((float) => float * 0.01)
// Ex3: Using Box, refactor applyDiscount (hint: each variable introduces a new Box)
// =========================
const applyDiscount_ = (price, discount) => {
const cents = moneyToFloat(price)
const savings = percentToFloat(discount)
return cents - cents * savings
}
const applyDiscount = (price, discount) =>
Box(price)
.map(moneyToFloat)
.fold((cents) =>
Box(discount)
.map(percentToFloat)
.fold((savings) => cents - cents * savings)
)
module.exports = {
moneyToFloat,
percentToFloat,
applyDiscount,
}