(str, rotation)
| 7 | * @return {string} - decrypted string |
| 8 | */ |
| 9 | const 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 | |
| 32 | export default caesarCipher |
no test coverage detected