Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
JavaScript Pig Latin Converter Optimizations

Total newb here...looking for some examples of optimizing this pigLatin converter.

function pigLatin(str) {

  var vowels = ["A", "E", "I", "O", "U", "a", "e", "i", "o", "u"];
   if (vowels.includes(str[0])) {
    str = str + "way";
    return str;
  }
 
  for (i = 0; i < str.length; i++) {
    if (vowels.includes(str[i])) {
      var flopStr = str.substring(0, [i]) + "ay";
      var newStr = str.substring([i]) + flopStr;
      return newStr;
    }
  }
  
  if (!vowels.includes(str) === true) {
    str = str + "ay";
    return str;
  }
}

I am pretty happy that I can at least write something that works. I do; however, need some guidance on other methods of accomplishing the same task.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is a solution without any looping, working with a regex and the index of the first vowel

function pigLatin(str) {

  let lC = str.toLowerCase()
  
  const vowels = ["a", "e", "i", "o", "u"];
  
  let regex = /[aeiou]/
  
  let fVI = lC.search(regex) // firstVowelIndex
  
  switch(fVI) {
    case 0: 
      return lC+'way';
    default:
      return lC.substring(fVI) + lC.substring(0,fVI) + 'ay'
  }
}

console.log(pigLatin('coding'))  // 'odingcay'

console.log(pigLatin('addict'))  // addictway

(an improvement you could adopt in your version is to convert the string to lower case and remove uppercase vowels from the array)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda