-
Notifications
You must be signed in to change notification settings - Fork 0
/
Conditioned.ts
60 lines (54 loc) · 1.46 KB
/
Conditioned.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
import {
ConditionConsequentLikePair,
ConditionConsequentPair,
Filtered,
First,
Mapped,
Scalar,
ScalarLike,
ScalarOf,
ToBool,
ToConditionConsequentPair
} from '@main';
/**
* Conditional scalar.
*/
export class Conditioned<T> implements Scalar<T> {
/**
* Condition/consequent pairs.
*/
private readonly firstConditionConsequent: Scalar<IteratorResult<ConditionConsequentPair<T>>>;
/**
* Fallback value when all conditions are false.
*/
private readonly alternative: Scalar<T>;
/**
* Ctor.
*
* @param alternative Fallback value when all conditions are false.
* @param conditionConsequents Condition/consequent pairs.
*/
constructor(alternative: ScalarLike<T>, ...conditionConsequents: ConditionConsequentLikePair<T>[]) {
this.firstConditionConsequent =
new First(
new Filtered(
new Mapped(conditionConsequents, new ToConditionConsequentPair<T>()),
new ToBool()
)
);
this.alternative = new ScalarOf(alternative);
}
/**
* Type determinant.
*/
public isScalar(): true {
return true;
}
/**
* Gets the value.
*/
public value(): T {
const first: IteratorResult<ConditionConsequentPair<T>> = this.firstConditionConsequent.value();
return !first.done ? first.value[1].value() : this.alternative.value();
}
}