I have been struggling with a function that I believe could be written more effectively. My goal is to simplify it while still maintaining its functionality.
function changeLetters(text) {
text = text.toLowerCase();
for (var i = 0; i < text.length; i++) {
var alphabet = advanced.checked ? alphabets[text[i]] || alphabets2[text[i]] : alphabets[text[i]];
if (alphabet) {
text = text.replace(text[i], alphabet);
}
}
return text;
}
One possible alternative approach is as follows:
function changeLetters(text) {
var alphabets = advanced.checked ? alphabets || alphabets2 : alphabets;
return text.toLowerCase().replace(/[a-z]/g, function(letter) {
return alphabets[letter] || letter;
});
}
However, the issue with the second function is that it does not properly check the alphabet
and alphabet2
objects when the advanced
option is selected. In other words, this line of code
advanced.checked ? alphabets || alphabets2 : alphabets
does not function as intended.
Is there a way to streamline this function further? Any suggestions are appreciated.
- demo - http://jsbin.com/AREZoCig/6/