JS1K

#2: the original

Source description for demo by Pinhas.

// 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);