make a function that translates a sentence into pig lating in javascript
index.tsx
functiontoPigLatin(sentence) {
const vowels = ['a', 'e', 'i', 'o', 'u'];
// Split the sentence into an array of wordsconst words = sentence.toLowerCase().split(' ');
// Loop through each word in the array and translate to pig latinconst translatedWords = words.map(word => {
// If the word starts with a vowel, just add 'way' to the endif (vowels.includes(word[0])) {
return`${word}way`;
} else {
// If the word starts with a consonant, find the index of the first vowelconst 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 sentencereturn 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"