forked from DrBoolean/spotify-fp-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
monoid.js
85 lines (69 loc) · 1.14 KB
/
monoid.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const Sum = x =>
({
x,
concat: ({x: y}) => Sum(x + y),
inspect: () => `Sum(${x})`
})
Sum.empty = () => Sum(0)
const Product = x =>
({
x,
concat: ({x: y}) => Product(x * y),
inspect: () => `Product(${x})`
})
Product.empty = () => Product(1)
const Any = x =>
({
x,
concat: ({x: y}) => Any(x || y),
inspect: () => `Any(${x})`
})
Any.empty = () => Any(false)
const All = x =>
({
x,
concat: ({x: y}) => All(x && y),
inspect: () => `All(${x})`
})
All.empty = () => All(true)
const Max = x =>
({
x,
concat: ({x: y}) => Max(x > y ? x : y),
inspect: () => `Max(${x})`
})
Max.empty = () => Max(-Infinity)
const Min = x =>
({
x,
concat: ({x: y}) => Min(x < y ? x : y),
inspect: () => `Min(${x})`
})
Min.empty = () => Min(Infinity)
const Pair = (x, y) =>
({
x,
y,
bimap: (f, g) => Pair(f(x), g(y)),
toList: () => [x, y],
concat: ({x: x1, y: y1}) =>
Pair(x.concat(x1), y.concat(y1)),
inspect: () => `Pair(${x}, ${y})`
})
const Fn = f =>
({
fold: f,
concat: o =>
Fn(x => f(x).concat(o.fold(x))),
inspect: () => `Fn(${f})`
})
module.exports = {
Sum,
Product,
Max,
Min,
Any,
All,
Pair,
Fn
}