Created
September 9, 2022 14:05
-
-
Save thedom85/d496f4991637106f94d600fda8fcd4a1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://www.codewars.com/kata/52742f58faf5485cae000b9a/train/javascript | |
function formatDuration(seconds) { | |
if(seconds == 0 ) return "now"; | |
t = Number(seconds); | |
var y = Math.floor(t / (3600*24*365)); | |
var d = y > 0 ? Math.floor(t % (3600*24*365) /(3600*24)) : Math.floor(t / (3600*24)); | |
var h = d > 0 ? Math.floor((t % (3600*24*365)) %(3600*24) /(3600) ) : Math.floor(t / 3600); | |
var m = Math.floor(t % 3600 / 60); | |
var s = Math.floor(t % 3600 % 60); | |
var display=[]; | |
y > 0 ? display.push(y + (y == 1 ? " year" : " years")) : ""; | |
d > 0 ? display.push(d + (d == 1 ? " day" : " days" )) : ""; | |
h > 0 ? display.push(h + (h == 1 ? " hour" : " hours")) : ""; | |
m > 0 ? display.push(m + (m == 1 ? " minute" : " minutes")) : ""; | |
s > 0 ? display.push(s + (s == 1 ? " second" : " seconds")) : ""; | |
return display.join(", ").replace(/,([^,]*)$/," and$1"); | |
} | |
log(1,formatDuration(1), "1 second"); | |
log(60,formatDuration(60), "1 minute"); | |
log(120,formatDuration(120), "2 minutes"); | |
log(61,formatDuration(61), "1 minute and 1 second"); | |
log(62,formatDuration(62), "1 minute and 2 seconds"); | |
log(121,formatDuration(121), "2 minutes and 1 second"); | |
log(122,formatDuration(122), "2 minutes and 2 seconds"); | |
log(120,formatDuration(120), "2 minutes"); | |
log(3600,formatDuration(3600), "1 hour"); | |
log(3662,formatDuration(3662), "1 hour, 1 minute and 2 seconds"); | |
log(15731080,formatDuration(15731080), "182 days, 1 hour, 44 minutes and 40 seconds"); | |
log(132030240,formatDuration(132030240), "4 years, 68 days, 3 hours and 4 minutes"); | |
log(3662,formatDuration(3662), "1 hour, 1 minute and 2 seconds"); | |
log(15731080,formatDuration(15731080), "182 days, 1 hour, 44 minutes and 40 seconds"); | |
log(205851834,formatDuration(205851834), "6 years, 192 days, 13 hours, 3 minutes and 54 seconds"); | |
log(3545364,formatDuration(3545364), "41 days, 49 minutes and 24 seconds"); | |
function log (a,b,c){ | |
console.log("formatDuration("+a+") = ",b," == ",c," - ",b==c) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment