1.3 KiB
1.3 KiB
title, tags, expertise, author, cover, firstSeen, lastUpdated
| title | tags | expertise | author | cover | firstSeen | lastUpdated |
|---|---|---|---|---|---|---|
| Caesar cipher | algorithm,string | beginner | maciv | blog_images/ancient-greek-building.jpg | 2020-12-28T20:10:18+02:00 | 2020-12-29T12:29:21+02:00 |
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 (
...) andArray.prototype.map()to iterate over the letters of the given string. - Use
String.prototype.charCodeAt()andString.fromCharCode()to convert each letter appropriately, ignoring special characters, spaces etc. - Use
Array.prototype.join()to combine all the letters into a string. - Pass
trueto the last parameter,decrypt, to decrypt an encrypted string.
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('');
};
caesarCipher('Hello World!', -3); // 'Ebiil Tloia!'
caesarCipher('Ebiil Tloia!', 23, true); // 'Hello World!'