MCPcopy
hub / github.com/TheAlgorithms/JavaScript / caesarCipher

Function caesarCipher

Ciphers/CaesarCipher.js:9–30  ·  view source on GitHub ↗
(str, rotation)

Source from the content-addressed store, hash-verified

7 * @return {string} - decrypted string
8 */
9const caesarCipher = (str, rotation) => {
10 if (typeof str !== 'string' || !Number.isInteger(rotation) || rotation < 0) {
11 throw new TypeError('Arguments are invalid')
12 }
13
14 const alphabets = new Array(26)
15 .fill()
16 .map((_, index) => String.fromCharCode(97 + index)) // generate all lower alphabets array a-z
17
18 const cipherMap = alphabets.reduce(
19 (map, char, index) => map.set(char, alphabets[(rotation + index) % 26]),
20 new Map()
21 )
22
23 return str.replace(/[a-z]/gi, (char) => {
24 if (/[A-Z]/.test(char)) {
25 return cipherMap.get(char.toLowerCase()).toUpperCase()
26 }
27
28 return cipherMap.get(char)
29 })
30}
31
32export default caesarCipher

Callers 1

Calls 2

setMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected