Search code examples
javascriptstringcharacterreduce

Return one or the other javascript


A function takes one string argument and outputs a string.

It should remove all vowels from the supplied string if the string contains mostly vowels, otherwise return the supplied string without modification.

Specification:

  • A string is considered to contain mostly vowels if it has more vowels (a, e, i, o, u) than consonants (b, c, d, f, g, h, j, k, l, m, n, p, q, r, s, t, v, w, x, y, z), ignoring all non-alphabetic characters from the count.
  • If a string contains mostly vowels, the result should have excess whitespace removed - there should be no leading or trailing whitespace, nor any double spaces within the returned string.
  • Strings may contain more than one word. Spaces between words must be preserved, except for when the entire word has been removed.

For example, the string "hello" would remain hello.

However, the string "adieu" would become d.

This is what I have tried to no success so far:

    function removeVowel(input) {
   //function that takes string as input
    //function returns an object containing vowel count without case in account.
    function vowelCount(input) {
        //to get vowel count using string.match
        let arrVowels =input.match(/[aeiouAEIOU]+?/g);

        //acc=accumulator, curr=current value
        let countVowCons= arrVowels.reduce(function (acc, curr) {
           if (typeof acc[curr.toLowerCase()] == 'undefined') {
               acc[curr.toLowerCase()] = 1;
           } 
           else {
               acc[curr.toLowerCase()] += 1;
           }
           return acc;
           // the blank object below is default value of the acc (accumulator)
           }, {}); 

        countVowCons.NonVowels= input.match(/[^aeiouAEIOU]+?/g).length;
             
        if(arrVowels > countVowCons.NoVowels) {
          //remove vowels from string & return new string
          const noVowels = input.replace(/[aeiou]/gi, '')
        } else {
          // return supplied string withoout modification
          return input
        }      
      } 
}

I know I´m doing a lot of things wrong, could anyone point me in the right direction?

Expected: "hello"
Received: undefined
Expected: "hrd d"
Received: undefined

Solution

  • const maybeDisemvowel = (originalString) => {
      const onlyConsonants = originalString.replace(/[^bcdfghjklmnpqrstvwxys]/gi, '')
      const onlyVowels = originalString.replace(/[^aeoiu]/gi, '')
      const withoutVowels = originalString.replace(/[aeoiu]/gi, '')
      const shouldReturnOriginal = onlyConsonants.length > onlyVowels.length
      return shouldReturnOriginal
        ? originalString
        : withoutVowels.trim().replace(/\s+/g, ' ')
    }
    
    console.log(maybeDisemvowel('  abb     b')) // no change
    console.log(maybeDisemvowel('aaaaaa   bbb aaa bbb b')) // change
    console.log(maybeDisemvowel('aa    ab       bba ')) // change