This pig latin exercise was fun.
This solution uses three regular expressions to check for:
- Vowels at the beginning of a string.
- One or more consonants at the beginning of a string.
- Vowels in general, but not including “y”.
Side Note: Regex101 is my go-to for figuring out regular expressions. I find it really helpful.
The second rendition of this solution uses the ternary operator to shorten the nested conditional syntax. It also removes the “crutch” of a return variable.
It looks like it could have been further reduced based on Solution 3 in the Challenge Guide. When I think about it, the “starts with consonant” regex is really just the negation of the vowel regex.
But anyway, let me know if you can find any bugs.
How it artedstway
const translatePigLatin = (str) => {
let startsWithVowelRegex = /^[aeiouy]/;
let startsWithNotAVowelRegex = /^[^aeiouy]+/;
let justVowelsRegex = /[aeiou]/;
let newStr = "";
if (startsWithVowelRegex.test(str) === true) {
newStr = str.concat("way");
} else {
let strOfStartingConsonants = "";
let startingConsonantLength = 0;
let strAsArray = str.split("");
let arrOfVowels = [];
strOfStartingConsonants = str.match(startsWithNotAVowelRegex)[0];
startingConsonantLength = strOfStartingConsonants.length;
console.log(`strOfStartingConsonants:${strOfStartingConsonants}`);
strAsArray.forEach((letter) => {
if (justVowelsRegex.test(letter) === true) arrOfVowels.push(letter);
});
if (arrOfVowels.length === 0) {
newStr = str.concat("ay");
} else {
newStr = newStr.concat(
str.substring(startingConsonantLength),
strOfStartingConsonants,
"ay"
);
}
}
console.log(`str:${str}`);
console.log(`newStr:${newStr}`);
return newStr;
};
How it’s oinggway
const translatePigLatin = (str) => {
let startsWithVowelRegex = /^[aeiouy]/;
let getConsonantsRegex = /^[^aeiouy]+/;
let justVowelsRegex = /[aeiou]/;
return startsWithVowelRegex.test(str) === true
? str.concat("way")
: justVowelsRegex.test(str) === false
? str.concat("ay")
: str
.substring(str.match(getConsonantsRegex)[0].length)
.concat(str.match(getConsonantsRegex)[0], "ay");
};
Console Tests
console.log(translatePigLatin("consonant") === "onsonantcay");
console.log(translatePigLatin("california") === "aliforniacay");
console.log(translatePigLatin("algorithm") === "algorithmway");
console.log(translatePigLatin("glove") === "oveglay");
console.log(translatePigLatin("schwartz") === "artzschway");
console.log(translatePigLatin("rhythm") === "rhythmay");