-
Notifications
You must be signed in to change notification settings - Fork 2
/
pigLatin.js
88 lines (72 loc) · 2.58 KB
/
pigLatin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// module.exports = pigPhrase;
// module.exports = unpigPhrase;
function submitPigPhrase() {
var input = document.getElementById('pigInput').value;
var translation = document.getElementById('translation');
var header = document.createElement('h3');
var text = document.createElement('p');
//clear previous translation from the DOM
translation.removeChild(translation.firstChild)
//Append newly translated phrase to the DOM
text.innerHTML = pigPhrase(input);
translation.appendChild(text);
}
/**
* Takes an sentence and converts each word into pig latin
* @param [String] phrase that will be converted into pig latin.
* @return [String] Phrase that has been translated into pig latin
*/
function pigPhrase (phrase) {
var sentence = phrase.split(' ');
var piggedPhrase = [];
for (var i = 0; i <= sentence.length - 1; i++) {
piggedPhrase.push(pigWord(sentence[i]));
};
return piggedPhrase.join(' ');
}
/**
* converts a pig latin phrase back into it's native language
* @param [String] Pig Latin phrase that will be converted back into the native language.
* @return [String] Phrase that has been translated into the native language.
*/
function unpigPhrase (phrase) {
var sentence = phrase.split(' ');
var unpiggedPhrase = [];
for (var i = 0; i <= sentence.length - 1; i++) {
unpiggedPhrase.push(unpigWord(sentence[i]));
};
return unpiggedPhrase.join(' ');
}
/**
* Takes a word and converts it into pig latin
* @param [string] This is the word that will be converted
* @return [string] Word that hass been converted into pig latin
*/
function pigWord (word) {
return word.slice(findFirstVowel(word), word.length) + '-' + word.slice( -word.length, findFirstVowel(word)) + 'ay';
}
/**
* Takes a word in pig latin and converts it into a human readable word
* @param [String] piggedWord that will be translated
* @return [String] Translated word
*/
function unpigWord ( piggedWord ) {
return piggedWord.slice( piggedWord.search('-') + 1, -2 ) + piggedWord.slice( 0, piggedWord.search('-'));
}
/**
* Finds the first vowel in a word
* @param [sting] word
* @return [int] position of the first vowel in the word
*/
function findFirstVowel (word) {
var vowels = ['a', 'e', 'i', 'o', 'u'];
for (var i = 0; i <= word.length - 1; i++) {
if (vowels.indexOf(word[i]) !== -1 ) {
return i;
}
}
return word.length;
}
// console.log(pigPhrase('I built a pig latin translator program'));
//
// console.log(unpigPhrase( 'is-Thay ig-Pay atin-Lay ase-phray ill-way e-bay anslated-tray ack-bay into-ay e-thay ative-nay anguage-lay -asay -aay ing.-stray' ));