Skip to content

Instantly share code, notes, and snippets.

@remynguyen96
Created February 8, 2021 09:09
Show Gist options
  • Select an option

  • Save remynguyen96/caacbe38c9458baf63d68577fb552444 to your computer and use it in GitHub Desktop.

Select an option

Save remynguyen96/caacbe38c9458baf63d68577fb552444 to your computer and use it in GitHub Desktop.
Basic encrypt and decrypt characters.
const encrypt = (text, k = 2) => {
const alphabet = [
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
];
let newText = '';
for (let char of text.toUpperCase()) {
// ASCII => A = 65 (https://www.w3schools.com/charsets/ref_html_ascii.asp);
const index = char.charCodeAt() - 65;
const newIndex = index + k;
const newChar = alphabet[newIndex];
newText += newChar;
}
return newText;
};
const encrypt2 = (text, k = 2) => {
const alphabet = [
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
];
let newText = '';
for (let char of text.toUpperCase()) {
let newIndex = k;
for (let i = 0; i < alphabet.length; i++) {
if (alphabet[i] === char) {
newIndex += i;
break;
}
}
const newChar = alphabet[newIndex];
newText += newChar;
}
return newText;
};
const decrypt = (text, k = 2) => {
const alphabet = [
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
];
let newText = '';
for (let char of text.toUpperCase()) {
const index = char.charCodeAt() - 65;
const newIndex = index - k;
const newChar = alphabet[newIndex];
newText += newChar;
}
return newText;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment