Back to Articles

Total Seconds to Nearest - typescript snippet

2020-09-21

Source Code

1const toFixed = (num: number, fixed: number): number => {
2 const re = new RegExp(`^-?\\d+(?:.\\d{0,${fixed || -1}})?`);
3 const x = num?.toString()?.match(re)?.[0];
4 if (!x) {
5 return num;
6 }
7
8 return Number.parseFloat(x);
9};
10
11/** convert total seconds to nearest unit (minutes, hours, days)
12 * @param seconds total seconds > 0
13 * @param precision optional precision of number
14 */
15export const secondsInNearest = ({
16 seconds,
17 precision = 2,
18}: {
19 seconds: number;
20 precision?: number;
21}) => {
22 if (seconds <= 0) {
23 return '0 seconds';
24 }
25
26 if (seconds < 90) {
27 return `${seconds} ${seconds === 1 ? 'second' : 'seconds'}`;
28 }
29
30 const mins = seconds / 60;
31 if (mins < 120) {
32 const v = toFixed(mins, precision);
33
34 return `${v} ${v === 1 ? 'minute' : 'minutes'}`;
35 }
36
37 const hours = mins / 60;
38 if (hours < 24) {
39 const v = toFixed(hours, precision);
40
41 return `${v} ${v === 1 ? 'hour' : 'hours'}`;
42 }
43
44 const days = hours / 24;
45 const v = toFixed(days, precision);
46
47 return `${v} ${v === 1 ? 'day' : 'days'}`;
48};
49

Execution Results

1secondsInNearest({ seconds: 1 }) === "1 second"
2secondsInNearest({ seconds: 60 }) === "60 seconds"
3secondsInNearest({ seconds: 100 }) === "1.66 minutes"
4secondsInNearest({ seconds: 120 }) === "2 minutes"
5secondsInNearest({ seconds: 500, precision: 0 }) === "8 minutes"
6secondsInNearest({ seconds: 500 }) === "8.33 minutes"
7secondsInNearest({ seconds: 12000 }) === "3.33 hours"
8secondsInNearest({ seconds: 86400 }) === "1 day"
9secondsInNearest({ seconds: 130000 }) === "1.5 days"