Reputation: 333
I have this function
for human readable duration.
function formatDuration (seconds) {
function numberEnding (number) {
return (number > 1) ? 's' : '';
}
if (seconds > 0){
var years = Math.floor(seconds / 31536000);
var days = Math.floor((seconds % 31536000) / 86400);
var hours = Math.floor(((seconds % 31536000) % 86400) / 3600);
var minutes = Math.floor((((seconds % 31536000) % 86400) % 60);
var second = (((seconds % 31536000) % 86400) % 3600) % 0;
var r = (years > 0 ) ? years + " year" + numberEnding(years) : "";
var x = (days > 0) ? days + " day" + numberEnding(days) : "";
var y = (hours > 0) ? hours + " hour" + numberEnding(hours) : "";
var z = (minutes > 0) ? minutes + " minute" numberEnding(minutes) : "";
var u = (second > 0) ? second + " second" + numberEnding(second) : "";
var str = r + x + y + z + u
return str
}
else {
return "now"}
}
}
How to put together r
, x
, y
, z
and u
like if there are more than two the last one always seperated by and
and the rest by comma
. The result is also a string
type.
example :
"year", "day", "hour", "minute" and "second"
"year", "day", "hour" and "minute"
"year"
"second"
"minute" and "second"
it goes on ...
I tried to put them into an array
to be able to use slice()
, but it does not return the desirable result for all possible combinations.
Thanks
Upvotes: 2
Views: 2790
Reputation: 1074495
You're on the right track with the array:
var a = [];
//...push things as you go...
var str = a.length == 1 ? a[0] : a.slice(0, a.length - 1).join(", ") + " and " + a[a.length - 1];
(Personally I prefer the Oxford comma ["this, that, and the other"], but your example doesn't use it, so this does what you asked instead...)
Live Example:
test(["this"]);
test(["this", "that"]);
test(["this", "that", "the other"]);
function test(a) {
var str = a.length == 1 ? a[0] : a.slice(0, a.length - 1).join(", ") + " and " + a[a.length - 1];
snippet.log("[" + a.join(", ") + "] => " + str);
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Upvotes: 4