Last active
January 1, 2016 12:15
-
-
Save Arkar-Aung/72ff63f9b3681ac8d9a0 to your computer and use it in GitHub Desktop.
A simple cipher in js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Cipher = (function () { | |
var shiftCharactor = function (charAt) { | |
if (charAt == 65) { | |
return 93; // A -> Z | |
} else if (charAt == 97) { | |
return 122; // a -> z | |
} else if (charAt == 93) { | |
return 65; // Z -> A | |
} else if (charAt == 122) { | |
return 97; // z -> a | |
} else { | |
return charAt + 1; | |
} | |
}; | |
var unshiftCharactor = function (charAt) { | |
charAt = charAt - 1; | |
if (charAt == 65) { | |
return 93; // A -> Z | |
} else if (charAt == 97) { | |
return 122; // a -> z | |
} else if (charAt == 93) { | |
return 65; // Z -> A | |
} else if (charAt == 122) { | |
return 97; // z -> a | |
} | |
return charAt; | |
}; | |
var encodeRecursive = function (str, index, result) { | |
if (index < str.length) { | |
var current = str.charCodeAt(index); | |
if ((current >= 65 && current < 78) || (current >= 97 && current < 110)) { | |
result += String.fromCharCode(shiftCharactor(current + 13)); | |
} else if ((current >= 65 && current >= 78) || (current >= 97 && current >= 110)) { | |
result += String.fromCharCode(shiftCharactor(current - 13)); | |
} else { | |
result += str[index]; | |
} | |
return encodeRecursive(str, ++index, result); | |
} | |
return result; | |
}; | |
var decodeRecursive = function (str, index, result) { | |
if (index < str.length) { | |
var current = str.charCodeAt(index); | |
if ((current >= 65 && current < 78) || (current >= 97 && current < 110)) { | |
result += String.fromCharCode(unshiftCharactor(current + 13)); | |
} else if ((current >= 65 && current >= 78) || (current >= 97 && current >= 110)) { | |
result += String.fromCharCode(unshiftCharactor(current - 13)); | |
} else { | |
result += str[index]; | |
} | |
return decodeRecursive(str, ++index, result); | |
} | |
return result; | |
}; | |
return { | |
encode: function (str) { | |
return encodeRecursive(str, 0, ""); | |
}, | |
decode: function (str) { | |
return decodeRecursive(str, 0, ""); | |
}, | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment