Skip to content

Commit 9bd9c27

Browse files
committed
🌟 feat: Implement timeToString function to format milliseconds into readable time
1 parent b33014a commit 9bd9c27

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

‎src/constants/time.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,36 @@ export const HOUR = 60 * MINUTE;
44
export const DAY = 24 * HOUR;
55
export const WEEK = 7 * DAY;
66
export const MONTH = 30 * DAY;
7+
8+
export const timeToString = (ms: number): string => {
9+
const timeUnits = [
10+
{ label: 'month', value: MONTH },
11+
{ label: 'week', value: WEEK },
12+
{ label: 'day', value: DAY },
13+
{ label: 'hour', value: HOUR },
14+
{ label: 'minute', value: MINUTE },
15+
{ label: 'second', value: SECOND },
16+
];
17+
18+
const formatTime = (remaining: number, units: typeof timeUnits): string => {
19+
if (remaining === 0 || units.length === 0) {
20+
return '';
21+
}
22+
23+
const [currentUnit, ...restUnits] = units;
24+
const count = Math.floor(remaining / currentUnit.value);
25+
const remainder = remaining % currentUnit.value;
26+
27+
if (count === 0) {
28+
return formatTime(remainder, restUnits);
29+
}
30+
31+
const currentString = `${count} ${currentUnit.label}${count === 1 ? '' : 's'}`;
32+
const restString = formatTime(remainder, restUnits);
33+
34+
return restString ? `${currentString}, ${restString}` : currentString;
35+
};
36+
37+
const result = formatTime(ms, timeUnits);
38+
return result || '0 seconds';
39+
};

0 commit comments

Comments
 (0)