-
Notifications
You must be signed in to change notification settings - Fork 447
Expand file tree
/
Copy pathpigLatin.js
More file actions
75 lines (61 loc) · 1.86 KB
/
pigLatin.js
File metadata and controls
75 lines (61 loc) · 1.86 KB
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
'use strict';
const assert = require('assert');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const pigLatin = (word) => {
let str = word;
// Convert string to lowercase
str = str.toString().toLowerCase();
// Initialize array of vowels
const vowels = ["a", "e", "i", "o", "u"];
// Initialize vowel index to 0
let vowelIndex = 0;
if (vowels.includes(str[0])) {
// If first letter is a vowel
return str + "yay";
} else {
// If the first letter isn't a vowel i.e is a consonant
for (let char of str) {
// Loop through until the first vowel is found
if (vowels.includes(char)) {
// Store the index at which the first vowel exists
vowelIndex = str.indexOf(char);
break;
}
}
// Compose final string
return str.slice(vowelIndex) + str.slice(0, vowelIndex) + "ay";
}
}
const getPrompt = () => {
rl.question('word ', (answer) => {
console.log( pigLatin(answer) );
getPrompt();
});
}
// Tests
if (typeof describe === 'function') {
describe('#pigLatin()', () => {
it('should translate a simple word', () => {
assert.equal(pigLatin('car'), 'arcay');
assert.equal(pigLatin('dog'), 'ogday');
});
it('should translate a complex word', () => {
assert.equal(pigLatin('create'), 'eatecray');
assert.equal(pigLatin('valley'), 'alleyvay');
});
it('should attach "yay" if word begins with vowel', () => {
assert.equal(pigLatin('egg'), 'eggyay');
assert.equal(pigLatin('emission'), 'emissionyay');
});
it('should lowercase and trim word before translation', () => {
assert.equal(pigLatin('HeLlO '), 'ellohay');
assert.equal(pigLatin(' RoCkEt'), 'ocketray');
});
});
} else {
getPrompt();
}