The Advanced Solution of "Pig Latin" can cause a endless loop

Tell us what’s happening:

The Advanced Solution of “Pig Latin” can cause a endless loop
if you input a word without vowels,the while will not stop logically,although it actually stops.

Your code so far


// function translatePigLatin(str) {
//   if(/[aeiou]/.test(str[0])){
//     return str= str +"way"
//   }else if(!/[aeiou]/g.test(str)){
//     return str= str +"way"
//   }else{
//   return str.replace(/(\w*?)(?=[aeiou])(.*)/,"$2$1ay");
//   }
// }


function translatePigLatin(str) {
    var strArr = [];
    var tmpChar;

    function isConsonant(char) {
        return !/[aeiou]/.test(char);
    }


    if (!isConsonant(str.charAt(0)))
        return str + "way";
    else
        strArr = str.split("");

//这里不会死循环吗
    while (isConsonant(strArr[0])) {
        tmpChar = strArr.shift();
        strArr.push(tmpChar);
    }

 return strArr.join("")+"ay";
}

// test here
console.log(translatePigLatin("cnmnmnccccc"))


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6726.400 QQBrowser/10.2.2265.400.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin

But isn’t that what @hugetiny is talking about? The Advanced Solution as presented on the Get a hint page will end up in the endless loop if a string with no vowels is passed to the function.

I believe the correct solution should be:

function translatePigLatin(str) {
  let strArr = [];
  let tmpChar;
  const vowels = /[aeiou]/i;

  function isConsonant( char, vowels = /[aeiou]/i ) {
    return !vowels.test( char );
  }

  if ( !isConsonant( str[0] ) )
    return str.concat('way');
  else if ( str.search( vowels ) === -1 )
    return str.concat('ay');
  else 
    strArr = str.split('');
  while ( isConsonant( strArr[0] ) ) {
    tmpChar = strArr.shift();
    strArr.push( tmpChar );
  }
    return strArr.join('').concat('ay');
}

Thank you for helping make FCC better. Bugs can be reported as GitHub Issues. Whenever reporting a bug, please check first that there isn’t already an issue for it and provide as much detail as possible.

1 Like