From a8b0ea1755a1a767ddbd33635d79fcb171569def Mon Sep 17 00:00:00 2001 From: Miguel Campos Date: Fri, 12 Jan 2024 21:41:06 -0800 Subject: [PATCH] add util methods for durations and percentages --- libs/util/numbers/src/lib/numbers.ts | 12 +++++++++++ libs/util/time/src/lib/time.ts | 32 ++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/libs/util/numbers/src/lib/numbers.ts b/libs/util/numbers/src/lib/numbers.ts index 9b7204080..be36c49ac 100644 --- a/libs/util/numbers/src/lib/numbers.ts +++ b/libs/util/numbers/src/lib/numbers.ts @@ -20,3 +20,15 @@ export function shorthandNumber(n: number): string { // else return n return `${n}`; } + +export function calculatePercentage(current?: number, max?: number) { + if (!current || !max) return 0; + if (current > max) return 0; + if (current < 0 || max < 0) return 0; + + return Math.min(Math.round((current / max) * 100), 100); +} + +export function toPercentage(current?: number, max?: number) { + return `${calculatePercentage(current, max)}%`; +} diff --git a/libs/util/time/src/lib/time.ts b/libs/util/time/src/lib/time.ts index c73f5f397..57a6b91c9 100644 --- a/libs/util/time/src/lib/time.ts +++ b/libs/util/time/src/lib/time.ts @@ -149,3 +149,35 @@ export const formatAmericanDate = (stamp: string) => { export const waitFor = (wait: number): Promise => { return new Promise((resolve) => setTimeout(resolve, wait)); }; + +/** + * @name timeUntil + * @definition used to calculate the amount of time until a specified date and time. + * @params {number} timestamp - the timestamp to calculate the amount of time until. + * @returns {number} the amount of time in milliseconds until the specified time. + */ + +export const timeUntil = (timestamp: number): number => { + return timestamp - Date.now(); +}; + +/** + * @name millisecondsToDuration + * @definition used to convert a number of milliseconds into a duration string. + * @params {number} milliseconds - the number of milliseconds to convert. + * @returns {string} the duration string. + * @example millisecondsToDuration(1000) // "00:00:01" + * @example millisecondsToDuration(1000 * 60) // "00:01:00" + * @example millisecondsToDuration(1000 * 60 * 60) // "01:00:00" + */ +export const millisecondsToDuration = (milliseconds: number): string => { + // count the number of hours, minutes, and seconds in the milliseconds + const hours = Math.floor(milliseconds / (1000 * 60 * 60)); + const minutes = Math.floor(milliseconds / (1000 * 60)) % 60; + const seconds = Math.floor(milliseconds / 1000) % 60; + + // print the hours, minutes, and seconds in the format HH:MM:SS + return `${hours.toString().padStart(2, '0')}:${minutes + .toString() + .padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; +};