0

I wanted to pluralize the string. I have written the function which can accept the single string or array of strings and return the pluralized one.

pluralizeTextArray: function(strArray) {
    var isNotArray = !_.isArray(strArray),
        temp = [];
    if (isNotArray) {
        temp[0] = strArray;
        strArray = temp;
    }
    var length = strArray.length,
        pluralizedArr = [],
        vowels = ['a','e','i','o','u'],
        lastChar = "",
        suffix = "s",
        str = "";

        for (var i = 0; i < length; i++) {
            str = strArray[i];
            lastChar = str[str.length - 1];
            switch (lastChar) {
                case 's':
                    if (!str.endsWith('ies')) {
                        suffix = 'es';
                    }
                    break;
                case 'y':
                    //ends in [consonant]y - add ies
                    //ends in [vowel]y - add 's' , 
                    //exception string ending with 'quy'
                    if ($.inArray(str[str.length - 2], vowels) === -1 ||
                       strObj.endsWith('quy')) {
                        str = str = _.initial(str).join(""); //removed last character
                         suffix = 'ies';
                    }
                    break;
                }
                pluralizedArr[i] = str+suffix;
            }
            retrun isNotArray ? pluralizedArr[0] : pluralizedArr;
        }

As in case if the input is not an array, i have to create one, which i am thinking is wrong. Can this code be optimized?

ajayv
  • 641
  • 6
  • 21
  • What happens with *radius* and *die`* (as in dice)? – Ed Heal Jul 10 '16 at 12:28
  • this function may not be handling all cases, but the cases i wanted to handle is handled by this function. I wanted to know that can it be written more better way ?? – ajayv Jul 10 '16 at 12:44
  • 1
    I'm voting to close this question as off-topic because the OP is essentially asking for a code review, so the question would be better placed at http://codereview.stackexchange.com. – nnnnnn Jul 10 '16 at 12:48
  • How does the function know if the input is a noun? Doesn't the line `temp[0] = strArray` give an error, considering that `temp` has the value `undefined` at that point? – nnnnnn Jul 10 '16 at 12:51
  • Try this [Javascript pluralize a string](http://stackoverflow.com/a/27194360/1766014) – AhmadReza Payan Jul 10 '16 at 12:51
  • @nnnnnn yes, that will give an error, correcting it. – ajayv Jul 10 '16 at 12:57

0 Answers0