-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathmaybe.js
42 lines (33 loc) · 770 Bytes
/
maybe.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
//http://jrsinclair.com/articles/2016/marvellously-mysterious-javascript-maybe-monad/
const Maybe = module.exports = function (val) {
this.__value = val
}
Maybe.of = function (val) {
return new Maybe(val)
}
Maybe.prototype.isNothing = function () {
return (this.__value === null || this.__value === undefined)
}
Maybe.prototype.map = function (f) {
if (this.isNothing()) {
return Maybe.of(null)
}
return Maybe.of(f(this.__value))
}
Maybe.prototype.foreach = function (f) {
if (!this.isNothing()) {
f(this.__value)
}
}
Maybe.prototype.orElse = function (d) {
if (this.isNothing()) {
return Maybe.of(d)
}
return this
}
Maybe.prototype.getOrElse = function (d) {
if (this.isNothing()) {
return d
}
return this.__value
}