Back

Total Seconds to Nearest - typescript snippet

2021-01-01

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 'Now';
24 }
25
26 if (seconds < 90) {
27 const v = toFixed(seconds, precision);
28
29 return `${v} ${v === 1 ? 'second' : 'seconds'}`;
30 }
31
32 const mins = seconds / 60;
33 if (mins < 120) {
34 const v = toFixed(mins, precision);
35
36 return `${v} ${v === 1 ? 'minute' : 'minutes'}`;
37 }
38
39 const hours = mins / 60;
40 if (hours < 24) {
41 const v = toFixed(hours, precision);
42
43 return `${v} ${v === 1 ? 'hour' : 'hours'}`;
44 }
45
46 const days = hours / 24;
47 const v = toFixed(days, precision);
48
49 return `${v} ${v === 1 ? 'day' : 'days'}`;
50};
51

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"