-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoptional.js
More file actions
47 lines (38 loc) · 896 Bytes
/
optional.js
File metadata and controls
47 lines (38 loc) · 896 Bytes
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
class Optional {
static empty = new Optional(null);
constructor(value) {
if (value === Optional.empty) {
this.value = null;
this.valueSet = false;
} else {
this.value = value;
this.valueSet = true;
}
}
isPresent() {
return this.valueSet;
}
get() {
if (!this.valueSet) {
throw new Error('No value present');
}
return this.value;
}
orElse(other) {
if (this.valueSet) {
return this.value;
}
return other;
}
toString() {
return this.value + '';
}
}
Array.prototype.findOptional = function (predicate) {
let index = this.findIndex(predicate);
if (index === -1) {
return new Optional(Optional.empty);
}
return new Optional(this[index]);
}
module.exports = Optional;