diff options
Diffstat (limited to 'packages/sortug/src/utils.ts')
| -rw-r--r-- | packages/sortug/src/utils.ts | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/packages/sortug/src/utils.ts b/packages/sortug/src/utils.ts new file mode 100644 index 0000000..687b8db --- /dev/null +++ b/packages/sortug/src/utils.ts @@ -0,0 +1,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`; + } +} |
