Skip to content

Instantly share code, notes, and snippets.

@kalouo
Created March 11, 2021 04:46
Show Gist options
  • Save kalouo/8c87efd11ad63e0c9111a2271b1fe99e to your computer and use it in GitHub Desktop.
Save kalouo/8c87efd11ad63e0c9111a2271b1fe99e to your computer and use it in GitHub Desktop.
/*
As a user I can enter a phrase "hello" and see it translated to Pig Latin "ellohay"
As a user I can enter a phrase "hello world" and see it translated to Pig Latin "ellohay orldway"
As a user I can enter a phrase "Hello World" and see it translated to Pig Latin "Ellohay Orldway"
As a user I can enter a phrase "Hello, world!" and see it translated to Pig Latin "Ellohay, orldway!"
As a user I can enter a phrase "eat apples" and see it translated to Pig Latin "eatay applesay"
As a user I can enter a phrase "quick brown fox" and see it translated to Pig Latin "ickquay ownbray oxfay"
*/
function transformSentence(sentence) {
const wordList = sentence.split(" ")
const transformedWordList = []
for (const word of wordList) {
const transformed = transformWord(word)
transformedWordList.push(transformed)
}
return transformedWordList.join(" ")
}
function transformWord(word:String) {
let result = word
let punctuation = ""
if (endsWithPunctation(word)){
punctuation = word.slice(-1)
result = word.slice(0, -1)
}
if (!startsWithVowel(word)){
result = startsWithConsonantCluster(word)?
result.slice(2) + result.slice(0, 2):
result.slice(1) + result[0]
}
if (doesStartUpperCase(word)){
result = result[0].toUpperCase() + result.slice(1).toLowerCase()
}
result = result + "ay" + punctuation
return result
}
function doesStartUpperCase(word) {
return word[0] === word[0].toUpperCase()
}
function endsWithPunctation(word) {
const lastChar = word.slice(-1)
return lastChar.match(/[a-z]/i) === null;
}
function startsWithVowel(word) {
return isVowel(word[0])
}
function isVowel(letter) {
const vowels = ['a', 'e', 'i', 'o', 'u']
return vowels.includes(letter.toLowerCase())
}
function startsWithConsonantCluster(word) {
const consonantClusters = ['qu', 'br']
return consonantClusters.includes(word.slice(0, 2))
}
console.log(transformSentence("hello"))
console.log(transformSentence("hello world"))
console.log(transformSentence("Hello World"))
console.log(transformSentence("Hello, World!"))
console.log(transformSentence("eat apples"))
console.log(transformSentence("quick brown fox"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment