translate sentence to piglatin in javascript

Here's an example code snippet that can translate a sentence to piglatin in JavaScript:

index.tsx
function toPigLatin(sentence) {
  const vowelSounds = ['a', 'e', 'i', 'o', 'u'];
  const words = sentence.split(' ');

  const pigLatinWords = words.map((word) => {
    if (vowelSounds.includes(word[0])) {
      return word + 'ay';
    } else {
      return word.slice(1) + word[0] + 'ay';
    }
  });

  return pigLatinWords.join(' ');
}

const sentence = 'This is a sample sentence in English.';
const pigLatin = toPigLatin(sentence);

console.log(pigLatin); // Output: "hisTay isay aay amplesay entencesay inay Englishay."
526 chars
20 lines

The toPigLatin function takes in a sentence as an argument and splits it into an array of individual words using the split() method. It then loops through each word using the map() method and applies the piglatin transformation logic.

If the first letter of the word is a vowel, it appends 'ay' to the end of the word. If the first letter is a consonant, it moves the first letter to the end of the word and appends 'ay'. Finally, it joins the piglatin words back into a sentence using the join() method and returns the translated sentence.

Note: This implementation is a simple one and may not work for all cases.

gistlibby LogSnag