Skip to content

Instantly share code, notes, and snippets.

@hcz
Last active January 13, 2018 00:34
Show Gist options
  • Select an option

  • Save hcz/c0d7a134dc3242ae491a74db94b1e0d5 to your computer and use it in GitHub Desktop.

Select an option

Save hcz/c0d7a134dc3242ae491a74db94b1e0d5 to your computer and use it in GitHub Desktop.
Caesar's cipher, the shift cipher
const shift = (cypherShift, alphabet, messageChar) => {
const charCode = (ch) => ch.toLowerCase().charCodeAt(0);
let begin = charCode(alphabet.from);
let end = charCode(alphabet.to);
[begin, end] = (begin > end) ? [end, begin] : [begin, end];
const alphabetLength = end - begin;
const shiftLength = cypherShift % alphabetLength;
if (alphabetLength === 0) return messageChar;
let result = charCode(messageChar);
if (result > end || result < begin) return messageChar;
result += shiftLength;
if (result > end) {
result = begin - 1 + result - end;
} else if (result < begin) {
result = end - 1 + begin - result;
}
return String.fromCharCode(result);
}
const cypher = (cypherShift, alphabet, message) => {
const shiftCurry = (messageChar) => shift(cypherShift, alphabet, messageChar);
return message
.toLowerCase()
.split('')
.map(shiftCurry)
.join('');
}
const decypher = (cypherShift, alphabet, message) => {
return cypher(-cypherShift, alphabet, message);
}
const CYPHER_SHIFT = 3;
const message = 'Good sense is the most equally distributed';
const A = 'a', Z = 'z';
const myCaesarCypher = cypher(CYPHER_SHIFT, {from: A, to: Z}, message);
console.log(message);
console.log(myCaesarCypher);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment