Skip to content

Instantly share code, notes, and snippets.

@thisandagain
Created February 21, 2013 17:43
Show Gist options
  • Save thisandagain/5006619 to your computer and use it in GitHub Desktop.
Save thisandagain/5006619 to your computer and use it in GitHub Desktop.
Encode / decode example for Paul
/**
* This function takes any words and splits them up into individual letters.
*
* @param {String} Input string
*
* @return {Array}
*/
function tokenize (input) {
return input.split('');
}
/**
* This function shifts any single letter and keyboard character "up" one.
*
* @param {String} Input character
*
* @return {String}
*/
function shift (input, offset) {
var code = input.charCodeAt(0) + offset;
return String.fromCharCode(code);;
}
/**
* Transforms any input string using the "shift" function.
*
* @param {String} Input string
*
* @return {String}
*/
function encode (input) {
// Split the input into "tokens" (individual characters)
var tokens = tokenize(input);
var output = [];
// Loop through each character and encode it
for (var i = 0; i < tokens.length; i++) {
var result = shift(tokens[i], 1);
output.push(result);
}
// Join all of the individual letter back together!
return output.join('');
}
/**
* Transforms any input string using the "shift" function.
*
* @param {String} Input string
*
* @return {String}
*/
function decode (input) {
// Split the input into "tokens" (individual characters)
var tokens = tokenize(input);
var output = [];
// Loop through each character and encode it
for (var i = 0; i < tokens.length; i++) {
var result = shift(tokens[i], -1);
output.push(result);
}
// Join all of the individual letter back together!
return output.join('');
}
var encoded = encode('hello world');
var decoded = decode(encoded);
alert(encoded + ' | ' + decoded);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment