Skip to content

Commit

Permalink
add util methods for durations and percentages
Browse files Browse the repository at this point in the history
  • Loading branch information
GGonryun committed Jan 13, 2024
1 parent 087f23c commit a8b0ea1
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
12 changes: 12 additions & 0 deletions libs/util/numbers/src/lib/numbers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)}%`;
}
32 changes: 32 additions & 0 deletions libs/util/time/src/lib/time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,35 @@ export const formatAmericanDate = (stamp: string) => {
export const waitFor = (wait: number): Promise<void> => {
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')}`;
};

0 comments on commit a8b0ea1

Please sign in to comment.