blob: 2f8000ce2af6d7dd5abd3764f139c07013a58163 (
plain)
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
83
|
import { Budget } from "./budget";
import Currency from "./currency/currency";
class BalanceToBudgetRatio {
toString(): string {
return this._ratio?.toFixed(2) ?? "";
}
public readonly recommendedAction: "arrears" | "save" | "spend" | null;
public readonly normalisedRatio: number | null;
private constructor(
private readonly _ratio: number | null,
private readonly _normalisationFactor: number,
) {
if (this._ratio === null) {
this.normalisedRatio = null;
this.recommendedAction = null;
return;
}
this.normalisedRatio = this._ratio * this._normalisationFactor;
if (this._ratio < 0) {
this.recommendedAction = "arrears";
} else if (this._ratio >= 1) {
this.recommendedAction = "spend";
} else {
this.recommendedAction = "save";
}
}
static new(balance: Currency, budget: Budget | null) {
if (budget === null || budget.quantity === 0 || budget.quantity === -0) {
return null;
}
return new BalanceToBudgetRatio(
balance.valueOf() / budget.quantity.valueOf(),
1,
);
}
static makeNormaliser(
...balanceToBudgetRatios: (BalanceToBudgetRatio | null)[]
): (r: BalanceToBudgetRatio | null) => BalanceToBudgetRatio {
const validRatios = balanceToBudgetRatios.filter(
(r) =>
r &&
r._ratio &&
!isNaN(r._ratio) &&
Infinity > r._ratio &&
-Infinity < r._ratio,
);
const maxAbsRatio = Math.max(
...validRatios.map((r) => Math.abs(r?._ratio ?? 0)),
);
const normalisationFactor = 1 / maxAbsRatio;
return (r) =>
new BalanceToBudgetRatio(r?._ratio ?? null, normalisationFactor);
}
static compare(
lhs: BalanceToBudgetRatio | null,
rhs: BalanceToBudgetRatio | null,
): number {
if (lhs === null || lhs._ratio === null) {
if (rhs === null || rhs._ratio === null) {
return 0;
}
return 1;
}
if (rhs === null || rhs._ratio === null) {
return -1;
}
return rhs._ratio - lhs._ratio;
}
}
export { BalanceToBudgetRatio };
|