forked from exercism/DEPRECATED.javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.js
More file actions
53 lines (42 loc) · 1.29 KB
/
example.js
File metadata and controls
53 lines (42 loc) · 1.29 KB
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
'use strict';
var ALPHABET = 'abcdefghijklmnopqrstuvwxyz';
function randomKey() {
var i, result = '';
for ( i = 0; i < 100; i++ ) {
result += ALPHABET[randomUpTo(ALPHABET.length)];
}
return result;
}
function randomUpTo(n) {
return Math.floor(Math.random() * n);
}
module.exports = function (userDefinedKey) {
var key;
function addEncodedCharacter(character, index, array) {
/*jshint validthis:true */
var i = ALPHABET.indexOf(character) + ALPHABET.indexOf(key[index]);
if (i >= ALPHABET.length) { i -= ALPHABET.length; }
this.push(ALPHABET[i]);
}
function addDecodedCharacter(character, index, array) {
/*jshint validthis:true */
var i = ALPHABET.indexOf(character) - ALPHABET.indexOf(key[index]);
if (i < 0) { i += ALPHABET.length; }
this.push(ALPHABET[i]);
}
this.encode = function (plaintext) {
var characters = [];
plaintext.split('').forEach( addEncodedCharacter, characters );
return characters.join('');
};
this.decode = function (ciphertext) {
var characters = [];
ciphertext.split('').forEach( addDecodedCharacter, characters );
return characters.join('');
};
this.key = userDefinedKey || randomKey();
key = this.key;
if (userDefinedKey === '' || key.match(/[\dA-Z]/)) {
throw new Error('Bad key');
}
};