Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit bd7475e

Browse files
authoredAug 8, 2020
Caeser cipher (trekhleb#517)
* added ceaserCipher algorithm * added ceaserCipher algorithm * fixed a typo
1 parent e54a3df commit bd7475e

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# caeserCipher Algorithm
2+
3+
caeserCipher Algorithm is a type of substitution algorithm in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on
4+
5+
## Complexity
6+
7+
- **Time:** `O(|n|)`
8+
- **Space:** `O(|n|)`
9+
## Example
10+
11+
The the following string `abcde` which is shifted by 1 will change to `bcdef`
12+
13+
## References
14+
15+
- [Wikipedia](https://en.wikipedia.org/wiki/Caesar_cipher)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import caeserCipher from '../caeserCipher';
2+
3+
describe('caeserCipher', () => {
4+
it('should subtitute each character by shifting up the alphabet by a given integer', () => {
5+
6+
7+
expect(caeserCipher('abcd', 1)).toBe('bcde');
8+
});
9+
10+
11+
it('should wrap back to the beginning of the alphabet if it shifts more than the 26 english alphabets', () => {
12+
13+
14+
expect(caeserCipher('xyz', 1)).toBe('yza');
15+
});
16+
it('should only shift letters and ignore non-alphabetic characters', () => {
17+
18+
expect(caeserCipher('gurer ner 9 qbtf!', 13)).toBe('there are 9 dogs!');
19+
});
20+
21+
it('should ignore case sensitivity', () => {
22+
23+
expect(caeserCipher('ABCD', 13)).toBe('bcde');
24+
});
25+
26+
27+
})
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {string} string
3+
* @param {number} shift
4+
* @return {string} result
5+
*/
6+
7+
export default function caeserCipher(string, shift) {
8+
// convert all alphabets in english language to an array
9+
const alphabetArr = "abcdefghijklmnopqrstuvwxyz".split("")
10+
// converting all the alphabets in string to lowercase
11+
string = string.toLowerCase()
12+
13+
let result = ""
14+
for (let i = 0; i < string.length; i++) {
15+
const currentChar = string[i]
16+
// checking index of character in the english alphabets
17+
const idx = alphabetArr.indexOf(currentChar)
18+
// skip character if the character is not an alphabet
19+
if (idx === -1) {
20+
result += currentChar
21+
continue;
22+
}
23+
//wrap up index, incase the next shift is beyond the 26th character
24+
const encodedIdx = (idx + shift) % 26
25+
result += alphabetArr[encodedIdx]
26+
27+
}
28+
// return the result of the shifted string
29+
return result
30+
}

0 commit comments

Comments
 (0)
Please sign in to comment.