3 ms·
I offer up this little item since I'm a bit of a stickler for applications using proper grammar. This is nothing complex but I use it all the time. I have vers
by 51Cards 15y ago
I offer up this little item since I'm a bit of a stickler for applications using proper grammar. This is nothing complex but I use it all the time. I have versions of the same routine in every language I work in.
function plural(count, itemName, pluralWord, singLead, plurLead, singFollow, plurFollow) {
if (((typeof pluralWord != 'undefined') && (typeof pluralWord.valueOf() == 'string')) && (pluralWord.length > 0))
var outP = count + ' ' + ((count == 1) ? itemName : pluralWord);
else
var outP = count + ' ' + itemName + ((count == 1) ? '' : 's');
var follow = (count == 1) ? singFollow : plurFollow;
outP += (((typeof follow != 'undefined') && (typeof follow.valueOf() == 'string')) && (follow.length > 0) ? ' ' + follow : '');
var lead = (count == 1) ? singLead : plurLead;
return (((typeof lead != 'undefined') && (typeof lead.valueOf() == 'string')) && (lead.length > 0) ? lead + ' ' : '') + outP;
}
Usage - first simple pluralization:
alert('There ' + plural(c,'dog','','is','are') + ' in my house');
c = 1 --> There is 1 dog in my house.
c <> 1 --> There are 2 dogs in my house.
alert(plural(c,'dog','','','','is','are') + ' in my house');
c = 1 --> 1 dog is in my house.
c <> 1 --> 2 dogs are in my house.
And for non-simple pluralization:
alert('There ' + plural(c,'company','companies','is','are') + ' on the list');
c = 1 --> There is 1 company on the list.
c <> 1 --> There are 2 companies on the list.
alert(plural(c,'company','companies','','','is','are') + ' on the list');
c = 1 --> 1 company is on the list.
c <> 1 --> 2 companies are on the list.