1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | export type Deadline = Date | number;
|
19 |
|
20 | export function minDeadline(...deadlineList: Deadline[]): Deadline {
|
21 | let minValue = Infinity;
|
22 | for (const deadline of deadlineList) {
|
23 | const deadlineMsecs =
|
24 | deadline instanceof Date ? deadline.getTime() : deadline;
|
25 | if (deadlineMsecs < minValue) {
|
26 | minValue = deadlineMsecs;
|
27 | }
|
28 | }
|
29 | return minValue;
|
30 | }
|
31 |
|
32 | const units: Array<[string, number]> = [
|
33 | ['m', 1],
|
34 | ['S', 1000],
|
35 | ['M', 60 * 1000],
|
36 | ['H', 60 * 60 * 1000],
|
37 | ];
|
38 |
|
39 | export function getDeadlineTimeoutString(deadline: Deadline) {
|
40 | const now = new Date().getTime();
|
41 | if (deadline instanceof Date) {
|
42 | deadline = deadline.getTime();
|
43 | }
|
44 | const timeoutMs = Math.max(deadline - now, 0);
|
45 | for (const [unit, factor] of units) {
|
46 | const amount = timeoutMs / factor;
|
47 | if (amount < 1e8) {
|
48 | return String(Math.ceil(amount)) + unit;
|
49 | }
|
50 | }
|
51 | throw new Error('Deadline is too far in the future')
|
52 | }
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 | const MAX_TIMEOUT_TIME = 2147483647;
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 | export function getRelativeTimeout(deadline: Deadline) {
|
72 | const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline;
|
73 | const now = new Date().getTime();
|
74 | const timeout = deadlineMs - now;
|
75 | if (timeout < 0) {
|
76 | return 0;
|
77 | } else if (timeout > MAX_TIMEOUT_TIME) {
|
78 | return Infinity
|
79 | } else {
|
80 | return timeout;
|
81 | }
|
82 | }
|
83 |
|
84 | export function deadlineToString(deadline: Deadline): string {
|
85 | if (deadline instanceof Date) {
|
86 | return deadline.toISOString();
|
87 | } else {
|
88 | const dateDeadline = new Date(deadline);
|
89 | if (Number.isNaN(dateDeadline.getTime())) {
|
90 | return '' + deadline;
|
91 | } else {
|
92 | return dateDeadline.toISOString();
|
93 | }
|
94 | }
|
95 | } |
\ | No newline at end of file |