a more readable way to do this?
I know there is a more readable way of writing this:
var string = (
(r.d != 0 ? r.d + (r.d == 1 ? ' day' : ' days') : '' ) +
(r.h != 0 ? r.h + (r.h == 1 ? ' hour' : ' hours开发者_StackOverflow社区') : '' ) +
(r.m != 0 ? r.m + (r.m == 1 ? ' minute' : ' minutes') : '' ) +
(r.s != 0 ? r.s + (r.s == 1 ? ' second' : ' seconds') : '' ));
Try something a bit more readable:
function singleOrPlural(val, single, plural){
if(val == 1)
return val + ' ' + single;
if(val > 1)
return val + ' ' + plural;
return '';
}
Use as:
singleOrPlural(r.day, 'day', 'days')
You can even go nuts and add this to the prototype
, and end up with r.days.singleOrPlural('day', 'days')
, but I don't think it's needed here.
I would use something like this:
function pluralize(aVal, aSuffix) {
var r = '';
if (aVal != 0) {
r = aVal + ' ' + aSuffix + (aVal > 1 ? 's' : '');
}
return r;
}
var string = pluralize(r.d, 'day') + pluralize(r.h, 'hour') +
pluralize(r.m, 'minute') + pluralize(r.s, 'second')
EDIT: renamed the function to pluralize
function getvalue(val, unit)
{
if(val>0)
return val + unit + (val > 1 ? 's' : '');
else
return '';
}
var string = gets(r.d, 'day') + gets(r.h, 'hour') + gets(r.m, 'minute') + gets(r.s, 'second');
精彩评论