Intermediate Algorithm Scripting: Pig Latin
Pig Latin is a way of altering English Words. The rules are as follows:
- If a word begins with a consonant, take the first consonant or consonant cluster, move it to the end of the word, and add "ay" to it.
- If a word begins with a vowel, just add "way" at the end.
translatePigLatin("california") should return "aliforniacay".
translatePigLatin("paragraphs") should return "aragraphspay".
translatePigLatin("glove") should return "oveglay".
translatePigLatin("algorithm") should return "algorithmway".
translatePigLatin("eight") should return "eightway".
Should handle words where the first vowel comes in the middle of the word. translatePigLatin("schwartz") should return "artzschway".
Should handle words without vowels. translatePigLatin("rhythm") should return "rhythmay".
function translatePigLatin(str) { return str.replace(/^(((?![aeiou])[a-z])+)(\w*)/, '$3$1') + ('aeiou'.split('').includes(str[0]) ? 'w' : '') + 'ay'; } [ 'california', 'paragraphs', 'glove', 'algorithm', 'eight', 'schwartz', 'rhythm', 'c2alifornia' ].forEach(word => console.log(translatePigLatin(word)));
Output:
aliforniacay aragraphspay oveglay algorithmway eightway artzschway rhythmay 2aliforniacay
No comments:
Post a Comment