Skip to content

Instantly share code, notes, and snippets.

@hassan-maavan
Created September 19, 2020 06:37
Show Gist options
  • Save hassan-maavan/720fa43b6bbcab3e1624503b44c5a5e3 to your computer and use it in GitHub Desktop.
Save hassan-maavan/720fa43b6bbcab3e1624503b44c5a5e3 to your computer and use it in GitHub Desktop.
Your task in order to complete this Kata is to write a function which formats a duration, given as a number of seconds, in a human-friendly way. The function must accept a non-negative integer. If it is zero, it just returns "now". Otherwise, the duration is expressed as a combination of years, days, hours, minutes and seconds. https://www.codew…
function formatDuration (sec) {
if(sec == 0)
return 'now';
let s = sec % 60;
let m = Math.floor((sec % 3600) / 60);
let h = Math.floor((sec % 86400) / 3600);
let d = Math.floor((sec % 31536000) / 86400);
let Y = Math.floor(sec / 31536000);
let string = '';
let flag = false;
if(Y) {
string += (Y == 1 ? (flag ? ', ':'') + Y + ' year' : (flag ? ', ':'') + Y + ' years');
flag = true;
}
if(d) {
string += (d == 1 ? (flag ? ', ':'') + d + ' day' : (flag ? ', ':'') + d + ' days');
flag = true;
}
if(h) {
string += (h == 1 ? (flag ? ', ':'') + h + ' hour' : (flag ? ', ':'') + h + ' hours');
flag = true;
}
if(m) {
string += (m == 1 ? (flag ? (s ? ', ' : ' and ') :'') + m + ' minute' : (flag ? (s ? ', ' : ' and ') :'') + m + ' minutes');
flag = true;
}
if(s) {
string += (s == 1 ? (flag ? ' and ':'') + s + ' second' : (flag ? ' and ':'') + s + ' seconds');
}
return string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment