-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathtime.ts
35 lines (33 loc) · 937 Bytes
/
time.ts
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
export interface Time {
hours: number;
minutes: number;
seconds: number;
}
/**
* Converts the given time to seconds in positive numerical format.
*
* @param time - Time to convert.
* @returns number Time in seconds.
*/
export function timeToSeconds(time: Time): number {
if (time) {
return Math.floor(time.seconds + time.minutes * 60 + time.hours * 3600);
}
throw Error('The given time is not valid.');
}
/**
* Converts from seconds to time as [[Time]].
*
* @param n - Number of seconds to convert (should be positive).
* @returns Time The converted time from the given number of seconds
*/
export function secondsToTime(n: number): Time {
if (n <= 0) {
return { hours: 0, minutes: 0, seconds: 0 };
}
const hours = Math.floor(n / 3600);
const restFromHours = n % 3600;
const minutes = Math.floor(restFromHours / 60);
const seconds = restFromHours % 60;
return { hours, minutes, seconds };
}