-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathresult-2.ts
67 lines (58 loc) · 1.2 KB
/
result-2.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
62
63
64
65
66
67
// An Option<T> class similar to Rust's Option type.
export class Option<T> {
static try<T>(fn: () => T): Option<T> {
try {
return new Option(fn())
} catch {
return new Option()
}
}
static from<T>(fn: <U>(unwrap: Option<U>) => U) {}
#ok: boolean
#value!: T
constructor()
constructor(value: T)
constructor(readonly value?: T) {
if (arguments.length == 0) {
this.#ok = false
} else {
this.#ok = true
this.#value = value!
}
}
unwrap(): T {
if (this.#ok) {
return this.#value
} else {
throw new TypeError("Attempted to unwrap empty Option.")
}
}
expect(text: string) {
if (this.#ok) {
return this.#value
} else {
throw new TypeError(`Expected ${text}; found empty Option.`)
}
}
unwrapOr(value: T): T {
if (this.#ok) {
return this.#value
} else {
return value
}
}
map<U>(fn: (value: T) => U): Option<U> {
if (this.#ok) {
return new Option(fn(this.#value))
} else {
return new Option()
}
}
flatMap<U>(fn: (value: T) => Option<U>): Option<U> {
if (this.#ok) {
return fn(this.#value)
} else {
return new Option()
}
}
}