- Author:
- Pinhas
- Twitter:
- @
- GitHub:
- Facebook:
- Google+:
- +
- Reddit:
- /r/
- Pouet:
- Website:
- Compo:
- classic
- Demo link:
- https://js1k.com/2010-first/demo/620
- Shortlink:
- https://js1k.com/620
- Blog post:
- please update here!
- Bytes:
- 140
- Chars:
- 140
- Submission
p=prompt,i=p("text"),k=-p("key"),a="abcdefghijklmnopqrstuvwxyz",m={},o="";for(c in a)m[a[c]]=a[(c-k)%26];for(c in i)o+=m[i[c]]||" ";alert(o)
- Description
- Cesar cipher (http://en.wikipedia.org/wiki/Caesar_cipher) encryption and decryption.
Handles lower case letters a..z only. Any other character will be replaced by a space.
For decryption enter the key as a negative number.
Based on Eleasar's morse encoder (http://js1k.com/demos#id533)
- Base64 encoded
cD1wcm9tcHQsaT1wKCJ0ZXh0Iiksaz0tcCgia2V5IiksYT0iYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoiLG09e30sbz0iIjtmb3IoYyBpbiBhKW1bYVtjXV09YVsoYy1rKSUyNl07Zm9yKGMgaW4gaSlvKz1tW2lbY11dfHwiICI7YWxlcnQobyk=
- Original source
// get the input string
var input = prompt("text");
// get the key and convert it to a negative number
// (why negative? see comment below)
var key = -prompt("key");
var output = "";
// create substitution map
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var map = {};
for (var index in alphabet) {
// index is a string, so (index + key) would result in a string.
// On the other hand (index - key) will result in a number. So
// if key is the negative value from the user input, (index - key)
// will give the correct number.
map[alphabet[index]] = alphabet[(index - key) % 26];
}
// replace any character with its substitution or a space character if no
// substitution exists
for (index in input) {
output += map[input[index]] || " ";
}
alert(output);