Skip to content

Commit 04ca956

Browse files
Merge pull request #528 from Saulo8732/master
Caesar Cipher in JavaScript
2 parents 79cb944 + da7d3c1 commit 04ca956

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
var str = "abc test string";
2+
var amount = 1;
3+
4+
console.log(cipher(str, amount));
5+
6+
function cipher(str, amount) {// Wrap the amount
7+
if (amount < 0)
8+
return caesarShift(str, amount + 26);
9+
10+
// Make an output variable
11+
var output = '';
12+
13+
// Go through each character
14+
for (var i = 0; i < str.length; i ++) {
15+
16+
// Get the character we'll be appending
17+
var c = str[i];
18+
19+
// If it's a letter...
20+
if (c.match(/[a-z]/i)) {
21+
22+
// Get its code
23+
var code = str.charCodeAt(i);
24+
25+
// Uppercase letters
26+
if ((code >= 65) && (code <= 90))
27+
c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
28+
29+
// Lowercase letters
30+
else if ((code >= 97) && (code <= 122))
31+
c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
32+
33+
}
34+
35+
// Append
36+
output += c;
37+
38+
}
39+
40+
// All done!
41+
return output;
42+
}

0 commit comments

Comments
 (0)