Skip to content

Instantly share code, notes, and snippets.

@kcrwfrd
Last active August 29, 2015 14:23
Show Gist options
  • Save kcrwfrd/3b5c79c84acd30e291b5 to your computer and use it in GitHub Desktop.
Save kcrwfrd/3b5c79c84acd30e291b5 to your computer and use it in GitHub Desktop.
Encode or decode rot13
# To run tests:
# npm install -g jasmine-node
# jasmine-node --color --coffee --matchall --autotest rot13.coffee
###
@name translateChar
@description
Encodes or decodes a single character either to or from rot13
@param char {String} - Must be exactly 1 character
@returns {String}
###
translateChar = (char) ->
throw Error "Invalid length: #{char.length}" if char.length isnt 1
alphabet = 'abcdefghijklmnopqrstuvwxyz'
lowercase_char = char.toLowerCase()
index = alphabet.indexOf lowercase_char
is_uppercase = char isnt lowercase_char
# No matching letter found. Could be a space, punctuation, etc.
# We'll just return the original character.
return char if index < 0
translated_index = index - 13
if translated_index < 0
translated_index = 26 + translated_index
translated_char = alphabet[translated_index]
if is_uppercase
return translated_char.toUpperCase()
else
return translated_char
###
@name rot13
@description
Encodes or decodes a string to or from rot13
@param {String} input
@returns {String}
###
rot13 = (input) ->
result = ''
for char in input
result += translateChar(char)
return result
describe 'rot13:', ->
it 'Should decode a rot13 string.', ->
result = rot13 'Fraq hf gur pbqr lbh hfrq gb qrpbqr guvf zrffntr'
expect(result).toEqual 'Send us the code you used to decode this message'
it 'Should encode a normal string to rot13.', ->
result = rot13 'Send us the code you used to decode this message'
expect(result).toEqual 'Fraq hf gur pbqr lbh hfrq gb qrpbqr guvf zrffntr'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment