Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancements to Caesar Cipher Implementation - CaesarCipher.js #1721

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 29 additions & 16 deletions Ciphers/CaesarCipher.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,42 @@
* @see - [wiki](https://en.wikipedia.org/wiki/Caesar_cipher)
* @param {string} str - string to be encrypted
* @param {number} rotation - the number of rotation, expect real number ( > 0)
* @param {string} [alphabet='abcdefghijklmnopqrstuvwxyz'] - Optional parameter to specify a custom alphabet
* @return {string} - decrypted string
*/
const caesarCipher = (str, rotation) => {
const caesarCipher = (str, rotation, alphabet = 'abcdefghijklmnopqrstuvwxyz') => {
if (typeof str !== 'string' || !Number.isInteger(rotation) || rotation < 0) {
throw new TypeError('Arguments are invalid')
throw new TypeError('Arguments are invalid');
}

const alphabets = new Array(26)
.fill()
.map((_, index) => String.fromCharCode(97 + index)) // generate all lower alphabets array a-z
const alphabets = Array.from(alphabet); // Allow custom alphabet
const alphabetLength = alphabets.length;

const cipherMap = alphabets.reduce(
(map, char, index) => map.set(char, alphabets[(rotation + index) % 26]),
new Map()
)
// Optimize rotation to handle rotations greater than alphabet length
const effectiveRotation = rotation % alphabetLength;

// Create cipher map to avoid recalculating for each character
const cipherMap = alphabets.reduce((map, char, index) => {
map.set(char, alphabets[(effectiveRotation + index) % alphabetLength]);
return map;
}, new Map());

return str.replace(/[a-z]/gi, (char) => {
if (/[A-Z]/.test(char)) {
return cipherMap.get(char.toLowerCase()).toUpperCase()
}
const isUpperCase = /[A-Z]/.test(char);
const lowerChar = char.toLowerCase();

// Check if the character is in the map (i.e., an alphabetic character)
if (cipherMap.has(lowerChar)) {
const cipheredChar = cipherMap.get(lowerChar);
return isUpperCase ? cipheredChar.toUpperCase() : cipheredChar;
}

return cipherMap.get(char);
});

};

return cipherMap.get(char)
})
}
// Example usage:
console.log(caesarCipher('Hello World!', 3)); // Khoor Zruog!

export default caesarCipher
export default caesarCipher;
Loading