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