-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoption.js
80 lines (78 loc) · 1.67 KB
/
option.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
const none = Symbol("None");
export class Option {
hasValue;
value;
constructor(value){
if(value instanceof Option){
this.value = value.value;
this.hasValue = value.hasValue;
} else {
this.value = value;
this.hasValue = value !== none;
}
}
andThen(func){
return this.hasValue ? new Option(func(this.value)) : this;
}
orElse(func){
return this.hasValue ? this : new Option(func());
}
filter(func){
return (this.hasValue && func(this.value))
? this
: Option.none();
}
filterNonEmpty(){
return this.filter(v => v && (Array.isArray(v) && v.length > 0) || (v instanceof Object && Object.keys(v).length > 0) || !(v instanceof Object));
}
filterTruthy(){
return this.filter(v => v);
}
filterNullable(){
return this.filter(v => v !== undefined && v !== null);
}
filterDefined(){
return this.filter(v => v !== undefined);
}
valueOrDefault(defaultValue){
return this.hasValue ? this.value : defaultValue
}
valueOfThrow(){
if(this.hasValue){
return this.value;
}
throw new Error("Cannot unwrap empty option.");
}
static some(value){
return new Option(value);
}
static none(){
return new Option(none);
}
static fromNonEmpty(value){
return Option.some(value).filterNonEmpty();
}
static fromTruthy(value){
return Option.some(value).filterTruthy();
}
static fromNullable(value){
return Option.some(value).filterNullable();
}
static fromDefined(value){
return Option.some(value).filterDefined();
}
static try(func){
try {
return Option.some(func());
} catch(ex){
return Option.none();
}
}
static async tryAsync(func){
try {
return Option.some(await func())
} catch(ex){
return Option.none();
}
}
};