Total newb here...looking for some examples of optimizing this pigLatin converter.
function pigLatin(str) {
var vowels = ["A", "E", "I", "O", "U", "a", "e", "i", "o", "u"];
if (vowels.includes(str[0])) {
str = str + "way";
return str;
}
for (i = 0; i < str.length; i++) {
if (vowels.includes(str[i])) {
var flopStr = str.substring(0, [i]) + "ay";
var newStr = str.substring([i]) + flopStr;
return newStr;
}
}
if (!vowels.includes(str) === true) {
str = str + "ay";
return str;
}
}
I am pretty happy that I can at least write something that works. I do; however, need some guidance on other methods of accomplishing the same task.
This is a solution without any looping, working with a regex and the index of the first vowel
function pigLatin(str) {
let lC = str.toLowerCase()
const vowels = ["a", "e", "i", "o", "u"];
let regex = /[aeiou]/
let fVI = lC.search(regex) // firstVowelIndex
switch(fVI) {
case 0:
return lC+'way';
default:
return lC.substring(fVI) + lC.substring(0,fVI) + 'ay'
}
}
console.log(pigLatin('coding')) // 'odingcay'
console.log(pigLatin('addict')) // addictway
(an improvement you could adopt in your version is to convert the string to lower case and remove uppercase vowels from the array)