-
Notifications
You must be signed in to change notification settings - Fork 1
/
Letter Changes.js
49 lines (46 loc) · 2.42 KB
/
Letter Changes.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
// Step By Step
function LetterChanges (str) {
// First we do a little meta-problem solving by setting up our alpha and newAlpha strings:
// Each character in alpha has the same index as the character coderbyte wants us to convert it to in newAlpha
// For instance, since we want all d's in our input string to be converted to e's, and then we want all vowels to be capitalized,
// we can "cheat" a by making alpha[3] equal to "d" and newAlpha[3] equal to "E".
var alpha = 'abcdefghijklmnopqrstuvwxyz';
var newAlpha = 'bcdEfghIjklmnOpqrstUvwxyzA';
// Next, we declare a variable to hold our answer
var answer = '';
// After that, we loop through each character in our input string
for (var i = 0; i < str.length; i++) {
// First, we use the indexOf method to check if the current character in our string is contained in alpha.
// Note that if the string you pass into indexOf isn't found, it will return -1. Otherwise, it will return the index of the first matching character found.
// For instance, alpha.indexOf("c") returns 2, while alpha.indexOf("C") returns -1.
if (alpha.indexOf(str[i]) !== -1) {
// If we find the character in the alpha string, we declare a variable to hold the index of the character.
// Note that this is an unnessary step that I do for the purposes of clarity. See the 2nd function for a faster implementation.
var index = alpha.indexOf(str[i]);
// Since we set up the characters in alpha to have the same index as the one we want to convert it to in newAlpha,
// all we have to do is access newAlpha at index to add the converted character to our answer variable.
answer += newAlpha[index];
// If str[i] doesn't appear in alpha...
} else {
// ...we add it to our answer string, leaving any characters we don't want to change untouched and in the same index in our answer variable as they were in our input string.
answer += str[i];
}
}
// Finally, we return our answer.
return answer;
}
// Without Comments
function LetterChanges (str) {
var alpha = 'abcdefghijklmnopqrstuvwxyz';
var newAlpha = 'bcdEfghIjklmnOpqrstUvwxyzA';
var answer = '';
for (var i = 0; i < str.length; i++) {
var index = alpha.indexOf(str[i]);
if (index !== -1) {
answer += newAlpha[index];
} else {
answer += str[i];
}
}
return answer;
}