-
Notifications
You must be signed in to change notification settings - Fork 2
/
timestamp.ts
70 lines (62 loc) · 1.68 KB
/
timestamp.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
import { Timestamp, TournamentFrequency } from "./types";
import { assertNever } from "./helpers";
export const ts = (date: Date): Timestamp => {
return date.getTime();
};
export const now = (): Timestamp => {
return ts(new Date());
};
export const addSeconds = (seconds: number, timestamp: Timestamp = now()) => {
return timestamp + seconds * 1000;
};
export const date = (timestamp: Timestamp): Date => {
return new Date(timestamp);
};
export const seconds = (from: Timestamp, to: Timestamp = now()): number => {
return to - from;
};
export const havePassed = (
seconds: number,
from: Timestamp,
to: Timestamp = now()
): boolean => {
return to - from >= seconds * 1000;
};
export const nextFrequency = (
frequency: TournamentFrequency,
ts: Timestamp
): Timestamp => {
const d = date(ts);
switch (frequency) {
case "minutely":
const seconds = 60 - d.getSeconds();
return ts + 1000 * seconds;
case "5minutely":
const minutes5 = 5 - (d.getMinutes() % 5);
return ts + 1000 * 60 * minutes5;
case "hourly":
const minutes = 60 - d.getMinutes();
return ts + 1000 * 60 * minutes;
case "daily":
const hours = 18 - d.getHours();
return (
ts +
1000 * 60 * 60 * (hours > 0 ? hours : hours + 18) -
1000 * 60 * d.getMinutes() -
1000 * d.getSeconds()
);
case "weekly":
return ts + 1000 * 60 * 60 * 24 * 7;
case "monthly":
return ts + 1000 * 60 * 60 * 24 * 30;
default:
return assertNever(frequency);
}
};
export const weekday = (ts: Timestamp): number => {
const day = date(ts).getDay() - 1;
switch (day) {
case -1: return 6;
default: return day;
}
};