-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptionFn.ts
More file actions
48 lines (38 loc) · 1001 Bytes
/
optionFn.ts
File metadata and controls
48 lines (38 loc) · 1001 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
48
export type Some<T> = {
_type: "Some"
value: T
}
export type None = {
_type: "None"
}
export type Option<T> = Some<T> | None
export function some<T>(value: T): Some<T> {
return { _type: "Some", value }
}
export function none(): None {
return { _type: "None" }
}
export function isSome<T>(option: Option<T>): option is Some<T> {
return option._type === "Some"
}
export function isNone<T>(option: Option<T>): option is None {
return option._type === "None"
}
export function map<T, K>(
option: Option<T>,
mapper: (value: T) => K,
): Option<K> {
return isSome(option) ? some(mapper(option.value)) : none()
}
export function bind<T, K>(
option: Option<T>,
binder: (value: T) => Option<K>,
): Option<K> {
return isSome(option) ? binder(option.value) : none()
}
export function defaultWith<T>(option: Option<T>, value: T): T {
return isSome(option) ? option.value : value
}
export function from<T>(value: T): Option<T> {
return value == null ? none() : some(value)
}