-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
executable file
·88 lines (74 loc) · 1.62 KB
/
index.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
86
87
88
exports.none = Object.create({
value: function() {
throw new Error('Called value on none');
},
isNone: function() {
return true;
},
isSome: function() {
return false;
},
map: function() {
return exports.none;
},
flatMap: function() {
return exports.none;
},
filter: function() {
return exports.none;
},
toArray: function() {
return [];
},
orElse: callOrReturn,
valueOrElse: callOrReturn
});
function callOrReturn(value) {
if (typeof(value) == "function") {
return value();
} else {
return value;
}
}
exports.some = function(value) {
return new Some(value);
};
var Some = function(value) {
this._value = value;
};
Some.prototype.value = function() {
return this._value;
};
Some.prototype.isNone = function() {
return false;
};
Some.prototype.isSome = function() {
return true;
};
Some.prototype.map = function(func) {
return new Some(func(this._value));
};
Some.prototype.flatMap = function(func) {
return func(this._value);
};
Some.prototype.filter = function(predicate) {
return predicate(this._value) ? this : exports.none;
};
Some.prototype.toArray = function() {
return [this._value];
};
Some.prototype.orElse = function(value) {
return this;
};
Some.prototype.valueOrElse = function(value) {
return this._value;
};
exports.isOption = function(value) {
return value === exports.none || value instanceof Some;
};
exports.fromNullable = function(value) {
if (value == null) {
return exports.none;
}
return new Some(value);
}