Created
March 20, 2018 08:18
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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';
}