Advertisement
Guest User

Handlebars helper for pluralizing most words

a guest
Sep 6th, 2013
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //dependencies: jQuery and string.js (http://stringjs.com/)
  2. //usage: {{pluralize num 'word'}}
  3.  
  4. Handlebars.registerHelper('pluralize', function(number, str) {
  5.     //doesn't handle weird words
  6.     var lastLetter = str[str.length - 1]
  7.         , strObj = S(str)
  8.         , vowels = ['a', 'e','i','o','u']
  9.         , root = str
  10.         , suffix = 's'
  11.     ;
  12.     if (+number !== 1) {
  13.         //possible weird cases
  14.         if (strObj.endsWith('man')) {
  15.             return strObj.chompRight('man').s + 'men';
  16.         }
  17.         if (str === 'person') {
  18.             return 'people';
  19.         }
  20.         //rule-based cases
  21.         switch (lastLetter) {
  22.             case 'o':
  23.             case 'x':
  24.             case 'z': //intentional fallthrough
  25.                 suffix = 'es';
  26.                 break;
  27.             case 'e':
  28.                 if (strObj.endsWith('fe')) {
  29.                     root = strObj.chompRight('fe').s;
  30.                     suffix = 'ves';
  31.                 }
  32.                 break;
  33.             case 'f':
  34.                 if (strObj.endsWith('arf') || strObj.endsWith('lf') || strObj.endsWith('af')) {
  35.                     root = strObj.chompRight('f').s;
  36.                     suffix = 'ves';
  37.                 }
  38.                 break;
  39.             case 'h':
  40.                 if (strObj.endsWith('sh') || strObj.endsWith('ch')) {
  41.                     suffix = 'es';
  42.                 }
  43.                 break;
  44.             case 's':
  45.                 if (!strObj.endsWith('ies')) {
  46.                     suffix = 'es';
  47.                 }
  48.                 break;
  49.             case 'y':
  50.                 //ends in [consonant]y
  51.                 if ($.inArray(str[str.length - 2], vowels) === -1 || strObj.endsWith('quy')) {
  52.                     root = strObj.chompRight('y').s;
  53.                     suffix = 'ies';
  54.                 }
  55.                 break;
  56.         }
  57.         return root + suffix;
  58.     }
  59.     return str;
  60. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement