A more readable way to do this?

I know there is a more readable way to write this:

var string = ( (rd != 0 ? rd + (rd == 1 ? ' day' : ' days') : '' ) + (rh != 0 ? rh + (rh == 1 ? ' hour' : ' hours') : '' ) + (rm != 0 ? rm + (rm == 1 ? ' minute' : ' minutes') : '' ) + (rs != 0 ? rs + (rs == 1 ? ' second' : ' seconds') : '' )); 
+6
javascript
source share
3 answers

Try something 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 crazy and add this to prototype , and you end up with r.days.singleOrPlural('day', 'days') , but I don't think it is needed here.

+6
source share

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(rd, 'day') + pluralize(rh, 'hour') + pluralize(rm, 'minute') + pluralize(rs, 'second') 

EDIT: renamed function to pluralize

+2
source share
 function getvalue(val, unit) { if(val>0) return val + unit + (val > 1 ? 's' : ''); else return ''; } var string = gets(rd, 'day') + gets(rh, 'hour') + gets(rm, 'minute') + gets(rs, 'second'); 
0
source share

All Articles