I'd like to offer you an alternative to your ROT13 function.
The alternative that I'm proposing is just a particular usage of a regular Caesar Cipher algorithm – a very simple form of encryption, in which each letter in the original message is shifted to the left or right by a certain number of positions.
To decrypt the message we simply shift back the letters the same number of positions.
Example:
- JAVASCRIPT becomes MDYDVFULSW if we shift all letters by 3 positions
- MDYDVFULSW turns back to JAVASCRIPT if we shift back all letters by 3 positions.
If after shifting a letter goes outside the range of letters, then the letter is wrapped around in alphabet. Example: Letter Z becomes C if is shifted by 3 positions.
This “wrap-around” effect means use of modulo. In mathematical terms, the above can be expressed as this:
En(x) = (x + n) mod 26
Dn(x) = (x – n) mod 26
Trying to implement this algorithm in JavaScript without the use of a proper modulo operator will produce either incorrect results or a very cryptic and difficult to understand code.
The biggest problem is that JavaScript doesn't contain a modulo operator. The % operator is just the reminder of the division - not modulo. However, it is pretty easy to implement modulo as a custom function:
// Implement modulo by replacing the negative operand
// with an equivalent positive operand that has the same wrap-around effect
function mod(n, p)
{
if ( n < 0 )
n = p - Math.abs(n) % p;
return n % p;
}
There are other ways of implementing modulo... if you are interested you can consult this article.
By using the mod function defined above, the code expresses the mathematical equation identically:
// Function will implement Caesar Cipher to
// encrypt / decrypt the msg by shifting the letters
// of the message acording to the key
function encrypt(msg, key)
{
var encMsg = "";
for(var i = 0; i < msg.length; i++)
{
var code = msg.charCodeAt(i);
// Encrypt only letters in 'A' ... 'Z' interval
if (code >= 65 && code <= 65 + 26 - 1)
{
code -= 65;
code = mod(code + key, 26);
code += 65;
}
encMsg += String.fromCharCode(code);
}
return encMsg;
}
To encode using ROT13 ... is now just a matter of choosing the appropriate key as indicated by algorithm name.