Algorithm 101: 3 Ways to Create Pig Latin
It is my pleasure to welcome you to this episode of Algorithm 101. If you have followed from the beginning, then this is your 10th Algorithm exercise and it features Pig Latin.
Pig Latin is a language game or argot in which words in English are altered, usually by adding a fabricated suffix or by moving the onset or initial consonant or consonant cluster of a word to the end of the word and adding a vocalic syllable to create such a suffix. For example, "Wikipedia" would become "Ikipediaway" (the "W" is moved from the beginning and has "ay" appended to create a suffix). - Wikipedia.
pigLatin("samson"); // 'amsonsay'
pigLatin("ebere"); // 'ebereway'
pigLatin("njoku"); // 'okunjay'
In how many ways can you achieve this programmatically? Let's checkout 3 ways!
Prerequisite
To benefit from this article, you need to have basic understanding of javascript's string and array methods.
Let's do this using:
- for...of...loop, toLowerCase(), match(), slice(), regular expression
function pigLatin(word) {
let regEx = /[aeiou]/gi;
let newWord = word.toLowerCase();
let charIndex;
if (newWord[0].match(regEx)) {
return newWord + "way";
}
for (char of newWord) {
if (char.match(regEx)) {
charIndex = newWord.indexOf(char);
break;
}
}
return newWord.slice(charIndex) + newWord.slice(0, charIndex) + "ay";
}
- for...in...loop, toLowerCase(), .split(), includes(), join(), push(), splice()
function pigLatin(word) {
let firstConsonants = [];
let latinWord = "";
let vowels = ["a", "e", "i", "o", "u"];
let wordArray = word.toLowerCase().split("");
if (vowels.includes(wordArray[0])) {
return wordArray.join("") + "way";
}
for (char in wordArray) {
if (!vowels.includes(wordArray[char])) {
firstConsonants.push(wordArray[char]);
} else {
latinWord =
wordArray.splice(char).join("") + firstConsonants.join("") + "ay";
break;
}
}
return latinWord;
}
- for...loop, toLowerCase(), .split(), match(), join(), push(), splice(), length, regular expression
function pigLatin(word) {
let firstConsonants = [];
let latinWord = "";
let regEx = /[aeiou]/gi;
let wordArray = word.toLowerCase().split("");
if (wordArray[0].match(regEx)) {
return wordArray.join("") + "way";
}
for (let char = 0; char <= wordArray.length; char++) {
if (!wordArray[char].match(regEx)) {
firstConsonants.push(wordArray[char]);
} else {
latinWord =
wordArray.splice(char).join("") + firstConsonants.join("") + "ay";
break;
}
}
return latinWord;
}
Conclusion
There are many ways to solve problems programmatically. I will love to know other ways you solved yours in the comment section.
If you have questions, comments or suggestions, please drop them in the comment section.
You can also follow and message me on social media platforms.
Thank You For Your Time.