Caeser cipher (#517)

* added ceaserCipher algorithm

* added ceaserCipher algorithm

* fixed a typo
This commit is contained in:
gifted-s 2020-08-08 10:51:22 +01:00 committed by GitHub
parent e54a3df231
commit bd7475ee19
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,15 @@
# caeserCipher Algorithm
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
## Complexity
- **Time:** `O(|n|)`
- **Space:** `O(|n|)`
## Example
The the following string `abcde` which is shifted by 1 will change to `bcdef`
## References
- [Wikipedia](https://en.wikipedia.org/wiki/Caesar_cipher)

View File

@ -0,0 +1,27 @@
import caeserCipher from '../caeserCipher';
describe('caeserCipher', () => {
it('should subtitute each character by shifting up the alphabet by a given integer', () => {
expect(caeserCipher('abcd', 1)).toBe('bcde');
});
it('should wrap back to the beginning of the alphabet if it shifts more than the 26 english alphabets', () => {
expect(caeserCipher('xyz', 1)).toBe('yza');
});
it('should only shift letters and ignore non-alphabetic characters', () => {
expect(caeserCipher('gurer ner 9 qbtf!', 13)).toBe('there are 9 dogs!');
});
it('should ignore case sensitivity', () => {
expect(caeserCipher('ABCD', 13)).toBe('bcde');
});
})

View File

@ -0,0 +1,30 @@
/**
* @param {string} string
* @param {number} shift
* @return {string} result
*/
export default function caeserCipher(string, shift) {
// convert all alphabets in english language to an array
const alphabetArr = "abcdefghijklmnopqrstuvwxyz".split("")
// converting all the alphabets in string to lowercase
string = string.toLowerCase()
let result = ""
for (let i = 0; i < string.length; i++) {
const currentChar = string[i]
// checking index of character in the english alphabets
const idx = alphabetArr.indexOf(currentChar)
// skip character if the character is not an alphabet
if (idx === -1) {
result += currentChar
continue;
}
//wrap up index, incase the next shift is beyond the 26th character
const encodedIdx = (idx + shift) % 26
result += alphabetArr[encodedIdx]
}
// return the result of the shifted string
return result
}