Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const LABELS = ['year', 'day', 'hour', 'minute', 'second'];
- function formatDuration (seconds) {
- if (seconds === 0) return 'now';
- let minutes = seconds / 60 >> 0;
- let hours = minutes > 59 ? minutes / 60 >> 0 : 0;
- let days = hours > 23 ? hours / 24 >> 0 : 0;
- const years = days > 364 ? days / 365 >> 0 : 0
- if (seconds > 59) seconds = seconds % 60;
- if (minutes > 59) minutes = minutes % 60;
- if (hours > 23) hours = hours % 24;
- if (days > 364) days = days % 365;
- return [years, days, hours, minutes, seconds]
- .map((item, idx) => item && (item > 1 ? item + ' ' + LABELS[idx] + 's' : item + ' ' + LABELS[idx]))
- .filter(item => item) // filter out zeroes
- .join(', ')
- .replace(/(^.+)([,])(.+$)/, '$1 and$3') // replace the "something, something" part at the end
- }
- const Test = {
- assertEquals(a, b) {
- if (a !== b) throw new Error(`Expected: ${b} but instead got: ${a}`);
- console.log(`Test passed: ${b}`);
- }
- };
- Test.assertEquals(formatDuration(1), "1 second");
- Test.assertEquals(formatDuration(62), "1 minute and 2 seconds");
- Test.assertEquals(formatDuration(120), "2 minutes");
- Test.assertEquals(formatDuration(3600), "1 hour");
- Test.assertEquals(formatDuration(3662), "1 hour, 1 minute and 2 seconds");
Add Comment
Please, Sign In to add comment