-
Notifications
You must be signed in to change notification settings - Fork 0
/
maybe.ts
61 lines (49 loc) · 1.08 KB
/
maybe.ts
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
enum MaybeKind {
Some,
None,
}
interface Some<T> {
readonly kind: MaybeKind.Some;
readonly val: T;
}
interface None {
readonly kind: MaybeKind.None;
}
type Maybe<T> = Some<T> | None;
function some<T>(val: T): Some<T> {
return { kind: MaybeKind.Some, val };
}
function none(): None {
return { kind: MaybeKind.None };
}
function isSome<T>(maybe: Maybe<T>): maybe is Some<T> {
return maybe.kind === MaybeKind.Some;
}
function orElse<T>(elseMaybe: Maybe<T>, maybe: Maybe<T>): Maybe<T> {
return isSome(maybe) ? maybe : elseMaybe;
}
function withDefault<T>(def: T, maybe: Maybe<T>): T {
return isSome(maybe) ? maybe.val : def;
}
function flatMap<T, U>(fn: (val: T) => Maybe<U>, maybe: Maybe<T>): Maybe<U> {
return isSome(maybe) ? fn(maybe.val) : none();
}
function map<T, U>(fn: (val: T) => U, maybe: Maybe<T>): Maybe<U> {
return flatMap(x => some(fn(x)), maybe);
}
function flatten<T>(maybe: Maybe<Maybe<T>>): Maybe<T> {
return flatMap(x => x, maybe);
}
export {
Some,
None,
Maybe,
isSome,
some,
none,
orElse,
withDefault,
flatMap,
map,
flatten,
};