Tell us what’s happening:
I solved this challenge of the intermediate algorithm lesson as below.I added some comments to explain what i am doing. Assuming a scenario i am solving this at my future job,would it be okay or i would have to find a more clear way to solve it?I feel a bit bad,cause i know there is a better way maybe to solve it but this is how i am thinking.Would appreciate any advice.Thanks!
Your code so far
function translatePigLatin(str) {
let myRegex=/^[aeiuo]/; //creating a regex with all vowels
let result=myRegex.test(str); //checking if starts with consonant or vowel
if(result){ //if str starts with vowel add 'way' at the end and return
return str+=("way");
}else{ //if str doesnt start with vowel then create an array with each letter
let newArr=str.split("");
if(newArr.every(item=>item!=="a"&&item!=="e"&&item!=="i"&&item!=="u"&&item!=="o")) return str+="ay"; //use every method to see if there is any vowel in the array,if not return the str with 'ay' added at the end
while(!result){ //if there is a vowel but it doesnt start with a vowel take the every first letter and transport it at the end of the array until the first letter is vowel.
let consonant = newArr.shift();
newArr.push(consonant);
str=newArr.toString();
result=myRegex.test(str);
}
newArr=newArr.join(""); //when first letter is a vowel,it breaks out of the while loop,joins the array to a string again,add 'ay' at the end and returns the str
return str=newArr+("ay");
}
}
translatePigLatin("consonant");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36
.
Challenge: Pig Latin
Link to the challenge: