Skip to content

Commit fa43e23

Browse files
committed
Pig Latin
1 parent 3c78c25 commit fa43e23

File tree

3 files changed

+85
-1
lines changed

3 files changed

+85
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,4 @@ Once inside, run the command below:
1616
7. Longest Word In a Sentence
1717
8. Search and Replace
1818
9. Anagram
19-
19+
10. Pig-latin

src/pigLatin/index.js

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
function pigLatin(str) {
2+
// Convert string to lowercase
3+
str = str.toLowerCase()
4+
// Initialize array of vowels
5+
const vowels = ["a", "e", "i", "o", "u"];
6+
// Initialize vowel index to 0
7+
let vowelIndex = 0;
8+
9+
if (vowels.includes(str[0])) {
10+
// If first letter is a vowel
11+
return str + "way";
12+
} else {
13+
// If the first letter isn't a vowel i.e is a consonant
14+
for (let char of str) {
15+
// Loop through until the first vowel is found
16+
if (vowels.includes(char)) {
17+
// Store the index at which the first vowel exists
18+
vowelIndex = str.indexOf(char);
19+
break;
20+
}
21+
}
22+
// Compose final string
23+
return str.slice(vowelIndex) + str.slice(0, vowelIndex) + "ay";
24+
}
25+
}
26+
27+
module.exports = pigLatin;
28+

src/pigLatin/solutions.js

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// IMPERATIVE APPROACH
2+
3+
function pigLatin(str) {
4+
// Convert string to lowercase
5+
str = str.toLowerCase();
6+
// Initialize array of vowels
7+
const vowels = ["a", "e", "i", "o", "u"];
8+
// Initialize vowel index to 0
9+
let vowelIndex = 0;
10+
11+
if (vowels.includes(str[0])) {
12+
// If first letter is a vowel
13+
return str + "way";
14+
} else {
15+
// If the first letter isn't a vowel i.e is a consonant
16+
for (let char of str) {
17+
// Loop through until the first vowel is found
18+
if (vowels.includes(char)) {
19+
// Store the index at which the first vowel exists
20+
vowelIndex = str.indexOf(char);
21+
break;
22+
}
23+
}
24+
// Compose final string
25+
return str.slice(vowelIndex) + str.slice(0, vowelIndex) + "ay";
26+
}
27+
}
28+
29+
// DECLARATIVE APPROACH
30+
function pigLatin(str) {
31+
return str
32+
.replace(/^([aeiouy])(.*)/, '$1$2way')
33+
.replace(/^([^aeiouy]+)(.*)/, '$2$1ay');
34+
}
35+
36+
// FOR...OF LOOP
37+
38+
function pigLatin(str){
39+
const strArr = str.split('')
40+
const isVowel = /[a,e,o,u,i]/gi
41+
let result = str
42+
if(!strArr[0].match(isVowel)){
43+
for(let i = 0; i < strArr.length; i++){
44+
if(!strArr[i].match(isVowel)){
45+
result = result.slice(1) + strArr[i]
46+
}
47+
else {
48+
result = result + 'ay'
49+
console.log(result)
50+
return result
51+
}
52+
}
53+
} else {
54+
return result + 'way'
55+
}
56+
}

0 commit comments

Comments
 (0)