-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.ts
82 lines (63 loc) · 2.16 KB
/
option.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { UnsafeExtractError } from "./errors.js";
import { Exception } from "./exceptions.js";
import type { Expression } from "./expression.js";
import { define, evaluate, fromValue } from "./expression.js";
import type { Result } from "./result.js";
import { Failure, Success } from "./result.js";
export type Option<A> = Some<A> | None;
abstract class OptionTrait {
public abstract readonly isSome: boolean;
public abstract readonly isNone: boolean;
public map<A, B>(this: Option<A>, morphism: (value: A) => B): Option<B> {
return this.isSome ? Some.of(morphism(this.value)) : None.instance;
}
public flatMap<A, B>(
this: Option<A>,
arrow: (value: A) => Option<B>,
): Option<B> {
return this.isSome ? arrow(this.value) : None.instance;
}
public filter<A>(
this: Option<A>,
predicate: (value: A) => boolean,
): Option<A> {
return this.isSome && predicate(this.value) ? this : None.instance;
}
public safeExtract<A>(this: Option<A>, defaultValue: Expression<A>): A {
return this.isSome ? this.value : evaluate(defaultValue);
}
public unsafeExtract<A>(
this: Option<A>,
exception: Expression<Exception | string>,
): A {
if (this.isSome) return this.value;
const error = evaluate(exception);
throw error instanceof Exception ? error : new UnsafeExtractError(error);
}
public toResult<E, A>(this: Option<A>, error: Expression<E>): Result<E, A> {
return this.isSome ? Success.of(this.value) : new Failure(error);
}
public *[Symbol.iterator]<A>(this: Option<A>): Generator<A, void, undefined> {
if (this.isSome) yield this.value;
}
}
export class Some<out A> extends OptionTrait {
public override readonly isSome = true;
public override readonly isNone = false;
public readonly value!: A;
public constructor(value: Expression<A>) {
super();
define(this, "value", value);
}
public static of<A>(value: A): Some<A> {
return new Some(fromValue(value));
}
}
export class None extends OptionTrait {
public override readonly isSome = false;
public override readonly isNone = true;
public constructor() {
super();
}
public static readonly instance = new None();
}