Guest User

Untitled

a guest
Mar 24th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. const LABELS = ['year', 'day', 'hour', 'minute', 'second'];
  2.  
  3. function formatDuration (seconds) {
  4. if (seconds === 0) return 'now';
  5.  
  6. let minutes = seconds / 60 >> 0;
  7. let hours = minutes > 59 ? minutes / 60 >> 0 : 0;
  8. let days = hours > 23 ? hours / 24 >> 0 : 0;
  9. const years = days > 364 ? days / 365 >> 0 : 0
  10.  
  11. if (seconds > 59) seconds = seconds % 60;
  12. if (minutes > 59) minutes = minutes % 60;
  13. if (hours > 23) hours = hours % 24;
  14. if (days > 364) days = days % 365;
  15.  
  16. return [years, days, hours, minutes, seconds]
  17. .map((item, idx) => item && (item > 1 ? item + ' ' + LABELS[idx] + 's' : item + ' ' + LABELS[idx]))
  18. .filter(item => item) // filter out zeroes
  19. .join(', ')
  20. .replace(/(^.+)([,])(.+$)/, '$1 and$3') // replace the "something, something" part at the end
  21. }
  22.  
  23. const Test = {
  24. assertEquals(a, b) {
  25. if (a !== b) throw new Error(`Expected: ${b} but instead got: ${a}`);
  26. console.log(`Test passed: ${b}`);
  27. }
  28. };
  29.  
  30. Test.assertEquals(formatDuration(1), "1 second");
  31. Test.assertEquals(formatDuration(62), "1 minute and 2 seconds");
  32. Test.assertEquals(formatDuration(120), "2 minutes");
  33. Test.assertEquals(formatDuration(3600), "1 hour");
  34. Test.assertEquals(formatDuration(3662), "1 hour, 1 minute and 2 seconds");
Add Comment
Please, Sign In to add comment