Skip to content

Instantly share code, notes, and snippets.

@dev-opus
Created May 6, 2021 23:11
Show Gist options
  • Save dev-opus/bb87df35afb535673e605a6d4d2300a5 to your computer and use it in GitHub Desktop.
Save dev-opus/bb87df35afb535673e605a6d4d2300a5 to your computer and use it in GitHub Desktop.
implementing caeser's cypher
/*
Caeser's Cypher
implemented by your's truly :)
*/
// since we are in a node environment, this is how we get input from the terminal
// note: i'm only get the first two arguments from the input array, excluding 'node app.js'
const [plainText, key] = process.argv.slice(2);
// makes sure plainText is in lowercase and trims
// out white lines from begining and end of plain text
// and converts plain text to an array of characters
const charArr = plainText.toLowerCase().trim().split('');
const charCodePlusKey = charArr.map(char => {
const code = char.charCodeAt(0);
// escape spaces and non-alphabet characters
if (code === 32 || code < 97 || code > 122) return char;
/*
what we are doing on line 55 is making
sure that the char generated is an
alphabetical character. i.e the char is
in the range of a-z.
let's see an example.
say at this instance of the iteration,
code = 99 ==> 99 ==> 'c' in unicode character mapping
key = 25 ==> simply shifteng code by the value of key
(i.e 99 + 25) gives us a code of 124 which maps to '|'
in the unicode character mapping set.
we don't want this, so we look for a way to make sure
that given any +ve key interger, shifting a char code by that
key always stays in the range of 97-122 i.e, a-z.
back to the arithmetic on line 55, subtracting 97 from 99
gives 2. i.e code = 99 ==> 99 - 97 = 2
ading 2 to 25 gives us 27, 2 + key ==> 2 + 25 = 27
taking the modulo (remainder of the division) of
27 and 26 gives 1 ==> 27 % 26 = 1
adding this to 97, gives 98.
now shiftedCode = 98, which maps to 'b' in the
unicode character mapping set.
this explanation is kinda "hazy", so if you need
further explanations, just google! :)
*/
const shiftedCode = ((code - 97 + parseInt(key)) % 26) + 97;
return String.fromCharCode(shiftedCode);
});
const cypher = charCodePlusKey.join('');
console.table({ plainText, cypher, key });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment