Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a more readable way to do this?

Tags:

javascript

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') : '' ) +
  (r.m != 0 ? r.m + (r.m == 1 ? ' minute' : ' minutes') : '' ) +
  (r.s != 0 ? r.s + (r.s == 1 ? ' second' : ' seconds') : '' ));
like image 807
Hailwood Avatar asked Aug 25 '10 05:08

Hailwood


People also ask

What makes text more readable?

Just make sure to use both capital and lowercase letters, as the difference in letter height makes scanning easier. For longer texts, you should use clear sans serif fonts. While serifs help the readability in printed media by supporting the reading flow, they do the opposite on the web.

What makes an article readable?

You can instantly tell whether this article you've opened is easy or hard to read—without even reading it. Easy-to-read articles have short and sweet paragraphs, legible fonts, well-structured subheadings, white space between paragraphs, graphics that break up long sections of text, and hyperlinks that say “hey!

What is a readable style?

10 tips for web writers Write in an approachable style Avoid writing in a tone that is too formal. Don't use bureaucratese, legalese, marketese, academic style or gobbledygook. Use everyday words Use words familiar to users of the content. Be careful using jargon or specialist language. Avoid idioms.


1 Answers

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.

like image 70
Kobi Avatar answered Oct 06 '22 00:10

Kobi