Skip to content

Instantly share code, notes, and snippets.

@nickihastings
Created March 20, 2018 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickihastings/b9354ffaa6fdb25df7fa26bd4f0c9341 to your computer and use it in GitHub Desktop.
Save nickihastings/b9354ffaa6fdb25df7fa26bd4f0c9341 to your computer and use it in GitHub Desktop.
Translate the provided string to pig latin. Pig Latin takes the first consonant (or consonant cluster) of an English word, moves it to the end of the word and suffixes an "ay". If a word begins with a vowel you just add "way" to the end. Input strings are guaranteed to be English words in all lowercase.
function translatePigLatin(str) {
var vowels = ['a','e','i','o','u'];
var strArr = str.split(''); //split the string into an array
//walk through the string array and test for vowels.
for(var i = 0; i<strArr.length; i++){
//if the letter is a vowel create the new string
if(vowels.includes(strArr[i])){
//if the first letter is a vowel just add 'way' to the end.
if(i == 0){
return str + 'way';
}
//otherwise create two substrings one from the point of the vowel to the end of the string
//the second from the beginning to the point of the vowel and then add 'ay to the end.
else{
return str.substr(i, strArr.length-1) + str.substr(0, i) + 'ay';
}
}
}
}
translatePigLatin("consonant");
@nilupultharanga
Copy link

function translatePigLatin(str) {
const vowels = ['a', 'e', 'i', 'o', 'u'];
let consonantCluster = '';

// If the word starts with a vowel, add "way" at the end
if (vowels.includes(str[0])) {
return str + 'way';
}

// If the word starts with a consonant, find the consonant cluster and move it to the end
for (let i = 0; i < str.length; i++) {
if (!vowels.includes(str[i])) {
consonantCluster += str[i];
} else {
return str.slice(i) + consonantCluster + 'ay';
}
}

// If the word does not contain any vowels, just add "ay" at the end
return str + 'ay';
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment