make a function that translates a sentence into pig lating in javascript

index.tsx
function toPigLatin(sentence) {
  const vowels = ['a', 'e', 'i', 'o', 'u'];
  // Split the sentence into an array of words
  const words = sentence.toLowerCase().split(' ');
  
  // Loop through each word in the array and translate to pig latin
  const translatedWords = words.map(word => {
    // If the word starts with a vowel, just add 'way' to the end
    if (vowels.includes(word[0])) {
      return `${word}way`;
    } else {
      // If the word starts with a consonant, find the index of the first vowel
      const firstVowelIndex = word.split('').findIndex(char => vowels.includes(char));
      // Move the consonant cluster before the first vowel to the end of the word and add 'ay'
      return `${word.slice(firstVowelIndex)}${word.slice(0, firstVowelIndex)}ay`;
    }
  });
  
  // Join the translated words array back into a sentence
  return translatedWords.join(' ');
}
888 chars
22 lines

Example usage:

index.tsx
const sentence = "The quick brown fox jumped over the lazy dog";
console.log(toPigLatin(sentence)); // "ethay ickquay ownbray oxfay umpedjay overway ethay azylay ogday"
169 chars
3 lines

gistlibby LogSnag