Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathCaesarCipher.js
More file actions
Latest commit
32 lines (27 loc) · 1.42 KB
/
Copy pathCaesarCipher.js
File metadata and controls
32 lines (27 loc) · 1.42 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
/**
* @function caesarsCipher
* @description - In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence.
* @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)
* @return {string} - decrypted string
*/
constcaesarCipher=(str,rotation)=>{
if(typeofstr!=='string'||!Number.isInteger(rotation)||rotation<0){
thrownewTypeError('Arguments are invalid')
}
constalphabets=newArray(26)
.fill()
.map((_,index)=>String.fromCharCode(97+index))// generate all lower alphabets array a-z
constcipherMap=alphabets.reduce(
(map,char,index)=>map.set(char,alphabets[(rotation+index)%26]),
newMap()
)
returnstr.replace(/[a-z]/gi,(char)=>{
if(/[A-Z]/.test(char)){
returncipherMap.get(char.toLowerCase()).toUpperCase()
}
returncipherMap.get(char)
})
}
exportdefaultcaesarCipher