Skip to content

Commit c79c8c8

Browse files
committed
Add caesar cipher algorithm.
1 parent d9b88bb commit c79c8c8

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

caesar-cipher/index.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const caesarCipher = (str, shift, decrypt = false) => {
2+
const s = decrypt ? (26 - shift) % 26 : shift;
3+
const n = s > 0 ? s : 26 + (s % 26);
4+
return [...str]
5+
.map((l, i) => {
6+
const c = str.charCodeAt(i);
7+
if (c >= 65 && c <= 90)
8+
return String.fromCharCode(((c - 65 + n) % 26) + 65);
9+
if (c >= 97 && c <= 122)
10+
return String.fromCharCode(((c - 97 + n) % 26) + 97);
11+
return l;
12+
})
13+
.join('');
14+
};
15+
16+
console.log(caesarCipher('aleksandar', -3));

0 commit comments

Comments
 (0)