Skip to content

Commit d718905

Browse files
authored
🔀 Merge pull request #1217 from altearius/FEATURE/temporal-plurality
🩹 Singular/plural forms for time counts.
2 parents 067076f + 03ae385 commit d718905

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

src/utils/MiscHelpers.js

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -141,12 +141,27 @@ export const getTimeDifference = (startTime, endTime) => {
141141
const msDifference = new Date(endTime).getTime() - new Date(startTime).getTime();
142142
const diff = Math.abs(Math.round(msDifference / 1000));
143143
const divide = (time, round) => Math.round(time / round);
144-
if (diff < 60) return `${divide(diff, 1)} seconds`;
145-
if (diff < 3600) return `${divide(diff, 60)} minutes`;
146-
if (diff < 86400) return `${divide(diff, 3600)} hours`;
147-
if (diff < 604800) return `${divide(diff, 86400)} days`;
148-
if (diff < 31557600) return `${divide(diff, 604800)} weeks`;
149-
if (diff >= 31557600) return `${divide(diff, 31557600)} years`;
144+
145+
const periods = [
146+
{ noun: 'second', value: 1 },
147+
{ noun: 'minute', value: 60 },
148+
{ noun: 'hour', value: 3600 },
149+
{ noun: 'day', value: 86400 },
150+
{ noun: 'week', value: 604800 },
151+
{ noun: 'fortnight', value: 1209600 },
152+
{ noun: 'month', value: 2628000 },
153+
{ noun: 'year', value: 31557600 },
154+
];
155+
156+
for (let idx = 0; idx < periods.length; idx += 1) {
157+
if (diff < (periods[idx + 1]?.value ?? Infinity)) {
158+
const period = periods[idx];
159+
const value = divide(diff, period.value);
160+
const noun = value === 1 ? period.noun : `${period.noun}s`;
161+
return `${value} ${noun}`;
162+
}
163+
}
164+
150165
return 'unknown';
151166
};
152167

0 commit comments

Comments
 (0)