blob: 687b8dbc6125b68ffd82646fd5d609e67fc8ab2a (
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
84
85
86
87
|
export function randomFromArray<T>(a: Array<T>): T {
const l = a.length;
const ind = Math.floor(Math.random() * l);
if (ind === l) return a[ind - 1];
else return a[ind];
}
export function randomFromArrayAcc<T>(a: Array<T>, s?: Set<T>): T {
const st = s ? s : new Set(a);
const l = a.length;
const ind = Math.floor(Math.random() * l);
const res = ind === l ? a[ind - 1] : a[ind];
if (st.has(res)) return randomFromArrayAcc(a, st);
else {
st.add(res);
// TODO have to return this too?
return res;
}
}
export function notRandomFromArray<T>(data: string, a: Array<T>): T {
const l = a.length;
const ind = hashTextToNumber(data, l - 1);
return a[ind];
}
function hashTextToNumber(text: string, max: number): number {
let hash = 0;
for (let i = 0; i < text.length; i++) {
const char = text.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash; // Convert to 32-bit integer
}
// Make sure the hash is positive and within the given range
return Math.abs(hash) % max;
}
// Format time for display (HH:MM:SS)
export const formatTime = (seconds: number): string => {
const hrs = Math.floor(seconds / 3600);
const mins = Math.floor((seconds % 3600) / 60);
const secs = Math.floor(seconds % 60);
return `${hrs.toString().padStart(2, "0")}:${mins
.toString()
.padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
};
export function date_diff(date: number, type: "short" | "long") {
const now = new Date().getTime();
const diff = now - new Date(date).getTime();
if (type == "short") {
return to_string(diff / 1000);
} else {
return to_string_long(diff / 1000);
}
}
function to_string(s: number) {
if (s < 60) {
return "now";
} else if (s < 3600) {
return `${Math.ceil(s / 60)}m`;
} else if (s < 86400) {
return `${Math.ceil(s / 60 / 60)}h`;
} else if (s < 2678400) {
return `${Math.ceil(s / 60 / 60 / 24)}d`;
} else if (s < 32140800) {
return `${Math.ceil(s / 60 / 60 / 24 / 30)}mo`;
} else {
return `${Math.ceil(s / 60 / 60 / 24 / 30 / 12)}y`;
}
}
function to_string_long(s: number) {
if (s < 60) {
return "right now";
} else if (s < 3600) {
return `${Math.ceil(s / 60)} minutes ago`;
} else if (s < 86400) {
return `${Math.ceil(s / 60 / 60)} hours ago`;
} else if (s < 2678400) {
return `${Math.ceil(s / 60 / 60 / 24)} days ago`;
} else if (s < 32140800) {
return `${Math.ceil(s / 60 / 60 / 24 / 30)} months ago`;
} else {
return `${Math.ceil(s / 60 / 60 / 24 / 30 / 12)} years ago`;
}
}
|