Skip to content

Commit

Permalink
convert util TimeUtils to TS (#19)
Browse files Browse the repository at this point in the history
* convert util TimeUtils to TS

* address review comments
  • Loading branch information
spasovski authored May 11, 2021
1 parent 5a9d2f6 commit 069a6af
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions packages/utils/src/TimeUtils.js → packages/utils/src/TimeUtils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
type TimeInSeconds = number;
type TimeString = `${string}:${string}:${string}`;

class TimeUtils {
static TIME_ZONES = Object.freeze([
{ label: 'Tokyo UTC+9 No DST', value: 'Asia/Tokyo' },
Expand Down Expand Up @@ -27,9 +30,9 @@ class TimeUtils {
* Pretty prints a time in seconds as a format like "1h 3m 23s", "32s"
* Seconds are padded after 60s, has elapsed to reduce width changes
* Minutes aren't paded, as thats a slower change
* @param {integer} time in seconds
* @param time in seconds
*/
static formatElapsedTime(time) {
static formatElapsedTime(time: TimeInSeconds): string {
if (!Number.isInteger(time)) {
throw new Error(
`${time} is not a number that can be expressed as a formatted time`
Expand All @@ -43,37 +46,40 @@ class TimeUtils {
return (
`${hours > 0 ? `${hours}h ` : ''}` +
`${mins > 0 || hours > 0 ? `${mins}m ` : ''}` +
`${time >= 60 ? `${seconds}s`.padStart(3, 0) : `${seconds}s`}`
`${time >= 60 ? `${seconds}s`.padStart(3, '0') : `${seconds}s`}`
);
}

/**
* Format the time into hh:mm:ss format, eg. '12:34:56'
* @param {integer} timeInSeconds in seconds
* @param timeInSeconds in seconds
*/
static formatTime(timeInSeconds) {
static formatTime(timeInSeconds: TimeInSeconds): string {
if (!Number.isInteger(timeInSeconds) || timeInSeconds < 0) {
throw new Error(
`${timeInSeconds} is not a number that can be expressed as a formatted time`
);
}

const hours = String(Math.floor(timeInSeconds / (60 * 60))).padStart(2, 0);
const hours = String(Math.floor(timeInSeconds / (60 * 60))).padStart(
2,
'0'
);

const divisorForMinutes = timeInSeconds % (60 * 60);
const minutes = String(Math.floor(divisorForMinutes / 60)).padStart(2, 0);
const minutes = String(Math.floor(divisorForMinutes / 60)).padStart(2, '0');

const divisorForSeconds = divisorForMinutes % 60;
const seconds = String(Math.ceil(divisorForSeconds)).padStart(2, 0);
const seconds = String(Math.ceil(divisorForSeconds)).padStart(2, '0');

return `${hours}:${minutes}:${seconds}`;
}

/**
* Parse time in seconds from the provided time string
* @param {string} timeString Time string in hh:mm:ss format
* @param timeString Time string in hh:mm:ss format
*/
static parseTime(timeString) {
static parseTime(timeString: TimeString): TimeInSeconds {
if (!timeString || typeof timeString !== 'string') {
throw new Error(`${timeString} is not a valid string`);
}
Expand Down

0 comments on commit 069a6af

Please sign in to comment.