|
| 1 | +/** |
| 2 | + * @function CaesarCipherEncrypt |
| 3 | + * @description - Encrypt using the Caesar Cipher |
| 4 | + * The Caesar Cipher is a kind of a substitution cipher. |
| 5 | + * Each character is shifted by a constant value that is defined as the key. |
| 6 | + * @param {string} str - string to be encrypted |
| 7 | + * @param {number} key - key value for encryption |
| 8 | + * @return {string} encrypted string |
| 9 | + */ |
| 10 | +export const CaesarCipherEncrypt = (str: string, key: number): string => { |
| 11 | + // We normalize the Shift value here to make sure that the key value always falls in the range of 0 to 25 |
| 12 | + const normalizedShift: number = ((key % 26) + 26) % 26; |
| 13 | + |
| 14 | + return str.replace(/[a-z]/gi, (char: string) => { |
| 15 | + const base = char <= "Z" ? 65 : 97; |
| 16 | + return String.fromCharCode((char.charCodeAt(0) - base + normalizedShift) % 26 + base); |
| 17 | + }) |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * @function CaesarCipherDecrypt |
| 22 | + * @description - Decrypt using the Caesar Cipher |
| 23 | + * Each character is shifted back by a constant value that is defined as the key. |
| 24 | + * @param {string} str - string to be decrypted |
| 25 | + * @param {number} key - key value used for encryption |
| 26 | + * @return {string} decrypted string |
| 27 | + */ |
| 28 | +export const CaesarCipherDecrypt = (str: string, key: number): string => { |
| 29 | + const normalizedShift: number = ((key % 26) + 26) % 26; |
| 30 | + |
| 31 | + return str.replace(/[a-z]/gi, (char: string) => { |
| 32 | + const base = char <= "Z" ? 65 : 97; |
| 33 | + return String.fromCharCode((char.charCodeAt(0) - base - normalizedShift) % 26 + base); |
| 34 | + }) |
| 35 | +} |
0 commit comments