-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathartichoke.js
executable file
·71 lines (66 loc) · 1.65 KB
/
artichoke.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
#!/usr/bin/env node
"use strict";
var program = require('commander');
var x = 'abcdefghijklmnopqrstuvwxyz&';
var matrix = [];
for (let i=0; i<x.length; i++) {
let cols = [];
for (let j=0; j<x.length; j++) {
cols.push(x[(j+i)%x.length]);
}
matrix.push(cols);
}
function encode(phrase, keyword='artichoke') {
let result = [];
let j = 0;
for (let i=0; i<phrase.length; i++) {
let c = phrase[i];
if (x.indexOf(c) < 0) {
result.push(c);
} else {
let r = keyword[j++%keyword.length];
let row = x.indexOf(r);
let col = (x.indexOf(c)+1)%x.length;
result.push(matrix[row][col]);
}
}
return result.join('');
}
function decode(phrase, keyword='artichoke') {
let result = [];
let j = 0;
for (let i=0; i<phrase.length; i++) {
let c = phrase[i];
if (x.indexOf(c) < 0) {
result.push(c);
} else {
let r = keyword[j++%keyword.length];
let row = x.indexOf(r);
for (var p=0; p<matrix[row].length; p++) {
if (matrix[row][p] == c) {
break;
}
}
p = p-1;
if (p<0) {
p = x.length-1; // handle negative -1
}
result.push(x[p]);
}
}
return result.join('');
}
program
.option('-k, --keyword <keyword>', 'keyword to use. Default "artichoke"')
.option('-e, --encode', 'encode the given phrase. Default')
.option('-d, --decode', 'decode the given phrase')
.arguments('<phrase>')
.action((phrase) => {
phrase = phrase.toLowerCase();
if (program.decode) {
console.log(decode(phrase, program.keyword));
} else {
console.log(encode(phrase, program.keyword));
}
})
.parse(process.argv);