//sample solution
/* this rotates a string: "lohel".rotate(3) is "hello" */
String.prototype.rotate = function(n) { // n is an integer
n %= this.length; // if n too large: modulo
var cut = n < 0 ? -n : this.length - n; // cutting point
return this.substr(cut) + this.substr(0,cut);
};
/*** Wrap everything below this line in a rot13_creator function! ***/
function rot13_creator(){
// compose the dictionary
var alph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var keys = (alph + alph.toLowerCase()).split("");
var values = (alph.rotate(13) +
alph.rotate(13).toLowerCase()).split("");
var rot13_dict = {}; // dict: {A:'N', ..., z:'m'}
keys.forEach( function(key, index){
rot13_dict[key] = values[index]; } );
// wrap dictionary in a mapping function
var rot13_map = function(character) {
return rot13_dict[character] || character;
};
// create the function we're actually interested in
var rot13 = function(text) {
return text.split("").map(rot13_map).join("");
};
return rot13();
}
No comments:
Post a Comment