-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathROT13.js
95 lines (80 loc) · 2.69 KB
/
ROT13.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* The function `reverse` computes the reversal
* of a given `String` (don't copy-pasta!)
*str_rot13
* @param {String} S to reverse
* @return {String}
*/
function reverse(S){
return S.split("").reverse().join(""); // splits the string, reverses it, and joins it back together.
// YOUR CODE HERE: NO INTERNET COPY-PASTA!
}
console.assert(reverse("") === ""); // Really?
console.assert(reverse("A") === "A"); // Jerk.
console.assert(reverse("cat") === "tac");
console.assert(reverse("ward") === "draw");
console.assert(reverse("books") === "skoob"); // Rokey, dokey...
console.assert(
reverse("we don't want no trouble") === "elbuort on tnaw t'nod ew"
);
/**
* Function `encode` accepts a `String` and produces
* the appropriate ROT13 "encoded" version, i.e. every
* character in `phrase` is "rotated" ahead by 13 characters.
*
* @see String.prototype.charCodeAt
* @see String.prototype.fromCharCode
* @see http://en.wikipedia.org/wiki/ROT13
*
* // Start with just `phrase`...
* @param {String} phrase to encode
* // Add `N` in part 2!
* // @param {Number} N rotation to apply, default 13
* @return {String} encoded with ROT13
*/
function encode (phrase, N){
//var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var message = "";
for (var i = 0; i < phrase.length; i++){ //loops the phrase
var charc = phrase[i].charCodeAt(0); // gives it a code
charc += 13; // adds 13 letters ahead
if (charc > 122){
message += String.fromCharCode((charc - 123) + 97); //to continue the loop
} else {
message += String.fromCharCode(charc);
// // } for (var i = 0; i < phrase.length; i++){
// // var charc = phrase[i].charCodeAt(0);
// // charc += N
// // if (charc > 122){
// // message += String.fromCharCode((charc - 123) + 97);
// } else {
// message += String.fromCharCode(charc);
}
}
return message;
}
/**
* Function `decode` accepts a `phrase` and `N` and
* decoded it appropriately, i.e. every _word_ character
* in `phrase` is rotated backward by `N` characters.
*
* @param {String} phrase to decode
* @param {Number} N rotation to apply, default 13
* @return {String} decoded by ROT-N
*/
function decode(phrase, N){
var message = " ";
for (var i = 0; i < phrase.length; i++) {
var charc = phrase[i].charCodeAt(0);
charc -= N;
if (charc < 97){
message += String.fromCharCode((charc - 123) + 97);
}
message += String.fromCharCode(charc);
} return message;
}
// Produce more examples, please...
console.assert(encode("hello") === "uryyb");
console.assert(encode("uryyb") === "hello");
console.assert(encode("hello", 2) === "jgnnq");
console.assert(decode("jgnnq", 2) === "hello");