Add caesarCipher
This commit is contained in:
committed by
Chalarangelo
parent
ebfc68e221
commit
33f3c8c83c
34
snippets/caesarCipher.md
Normal file
34
snippets/caesarCipher.md
Normal file
@ -0,0 +1,34 @@
|
||||
---
|
||||
title: caesarCipher
|
||||
tags: algorithm,string,beginner
|
||||
---
|
||||
|
||||
Encrypts or decrypts a given string using the Caesar cipher.
|
||||
|
||||
- Use the modulo (`%`) operator and the ternary operator (`?`) to calculate the correct encryption/decryption key.
|
||||
- Use the spread operator (`...`) and `Array.prototype.map()` to iterate over the letters of the given string.
|
||||
- Use `String.prototype.charCodeAt()` and `String.fromCharCode()` to convert each letter appropriately, ignoring special characters, spaces et.c
|
||||
- Use `Array.prototype.join()` to combine all the letters into a string.
|
||||
- Pass `true` to the last parameter, `decrypt`, to decrypt an encrypted string.
|
||||
|
||||
```js
|
||||
const caesarCipher = (str, shift, decrypt = false) => {
|
||||
const s = decrypt ? (26 - shift) % 26 : shift;
|
||||
const n = s > 0 ? s : 26 + (s % 26);
|
||||
return [...str]
|
||||
.map((l, i) => {
|
||||
const c = str.charCodeAt(i);
|
||||
if (c >= 65 && c <= 90)
|
||||
return String.fromCharCode(((c - 65 + n) % 26) + 65);
|
||||
if (c >= 97 && c <= 122)
|
||||
return String.fromCharCode(((c - 97 + n) % 26) + 97);
|
||||
return l;
|
||||
})
|
||||
.join('');
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
caesarCipher('Hello World!', -3); // 'Ebiil Tloia!'
|
||||
caesarCipher('Ebiil Tloia!', 23, true); // 'Hello World!'
|
||||
```
|
||||
Reference in New Issue
Block a user