Question about fromCharCode and ending an "if" statement

52 views Asked by At

I'm working on a simple cipher algorithm and I'm trying to figure out how to stop the if statement at character 122 (z) and start back at char 97 (a) once the character count exceeds 122. This is what I have so far and have looked around on MDN and W3 schools and haven't come up with anything.

enter code here
function simpleCipher(str) {

   var newString = [];

  for (var i = 0; i < str.length; i ++) {
     if (str.charCodeAt(i) > 97 || str.charCodeAt(i) < 122) {
       var convertString = String.fromCharCode(str.charCodeAt(i) + 4);
       var powerString = newString.push(convertString);
    } else {
      return;
    }
  } 
  return newString.join('');
}
1

There are 1 answers

2
Yola On

Use modular arithmetic.

var aPos = 97;
var zPos = 122;
var charsCount = zPos - aPos + 1;
...
if (aPos <= str.charCodeAt(i) && str.charCodeAt(i) <= zPos) { // probably you want && here
  var charNumber = str.charCodeAt(i) - aPos;
  var charNumberEncoded = (charNumber + 4) % charsCount;
  var convertString = String.fromCharCode(aPos + charNumberEncoded);
  var powerString = newString.push(convertString);
}

It is considered a good practice to give constants names and not use numbers in the code. Such numbers often referenced as magic numbers and make it harder to read the code.