-
Notifications
You must be signed in to change notification settings - Fork 12
/
morse.js
72 lines (62 loc) · 1.38 KB
/
morse.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
module.exports = {
encode: encode,
decode: decode,
map: map,
tree: tree
};
var map = require('./map');
var tree = require('./tree');
function encode (obj) {
return maybeRecurse(obj, encodeMorseString);
function encodeMorseString (str) {
var ret = str.split('');
for (var j in ret) {
ret[j] = map[ret[j].toUpperCase()] || '?';
}
return ret.join(' ');
}
}
function decode (obj, dichotomic) {
return maybeRecurse(obj, decodeMorseString);
function decodeMorseString (str) {
var ret = str.split(' ');
for (var i in ret) {
if (!dichotomic) {
ret[i] = decodeCharacterByMap(ret[i]);
} else {
ret[i] = decodeCharacterByDichotomy(ret[i]);
}
}
return ret.join('');
}
}
function maybeRecurse (obj, func) {
if (!obj.pop) {
return func(obj);
}
var clone = [];
var i = 0;
for (; i < obj.length; i++) {
clone[i] = func(obj[i]);
}
return clone;
}
function decodeCharacterByMap (char) {
for (var i in map) {
if (map[i] == char) {
return i;
}
}
return ' ';
}
function decodeCharacterByDichotomy (char) {
var sub = char.split('');
return traverseNodeWithCharacters(tree, sub);
function traverseNodeWithCharacters (node, chars) {
var cur = chars.shift();
if (!node[cur]) {
return node.stop || '?';
}
return traverseNodeWithCharacters(node[cur], chars);
}
}