Last active
February 24, 2019 22:16
-
-
Save okovalov/52a758837013464e3eac71c59455f932 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ceasarCipher = (str, num) => { | |
const alphabetArr = 'abcdefghijklmnopqrstuvwxyz'.split('') | |
let myNum = num % alphabetArr.length | |
const strArr = str.toLowerCase().split('') | |
let resArr = [] | |
for (let c in strArr) { | |
let letter = strArr[c] | |
const index = alphabetArr.indexOf(letter) | |
if (index < 0) { | |
resArr.push(letter) | |
continue | |
} | |
const newIndex = index + myNum | |
const pos = newIndex >= 0 ? | |
newIndex < alphabetArr.length ? | |
newIndex : | |
newIndex - alphabetArr.length | |
: alphabetArr.length + newIndex | |
if (str[c] === str[c].toUpperCase()) { | |
resArr.push(alphabetArr[pos].toUpperCase()) | |
continue | |
} | |
resArr.push(alphabetArr[pos]) | |
} | |
return resArr.join('') | |
} | |
let given = 'azyB ,Azyc' | |
let expected = 'yxwZ ,Yxwa' | |
let result = ceasarCipher(given, -262) | |
console.log(`with given '${given}' we expect '${expected}' and we got '${result}', they equlity is '${expected === result}' `) | |
given = 'azyB ,Azyc' | |
expected = 'cbaD ,Cbae' | |
result = ceasarCipher(given, 496) | |
console.log(`with given '${given}' we expect '${expected}' and we got '${result}', they equlity is '${expected === result}' `) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment