Skip to content

Instantly share code, notes, and snippets.

@okovalov
Last active February 24, 2019 22:16
Show Gist options
  • Save okovalov/52a758837013464e3eac71c59455f932 to your computer and use it in GitHub Desktop.
Save okovalov/52a758837013464e3eac71c59455f932 to your computer and use it in GitHub Desktop.
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