-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathltc.js
53 lines (52 loc) · 1.7 KB
/
ltc.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
module.exports.encode = s => {
try {
let dictionary = {},
out = [],
currentChar,
phrase = s[0],
code = 57344;
s = (s + "").split("");
for (let i = 1; i < s.length; i++) {
currentChar = s[i];
if (dictionary[phrase + currentChar] != null) {
phrase += currentChar;
} else {
out.push(phrase.length > 1 ? dictionary[phrase] : phrase.codePointAt(0));
dictionary[phrase + currentChar] = code;
code++;
phrase = currentChar;
}
}
out.push(phrase.length > 1 ? dictionary[phrase] : phrase.codePointAt(0));
return out.map(e => String.fromCodePoint(e)).join('');
} catch (error) {
throw new Error(error);
}
}
module.exports.decode = dataAsText => {
try {
let data = [...dataAsText].map(e => e.codePointAt(0)),
dictionary = {},
currentChar = String.fromCodePoint(data[0]),
oldPhrase = currentChar,
out = [currentChar],
code = 57344,
phrase;
for (let i = 1; i < data.length; i++) {
let currentCode = data[i];
if (currentCode < 57344) {
phrase = String.fromCodePoint(data[i]);
} else {
phrase = dictionary[currentCode] ? dictionary[currentCode] : (oldPhrase + currentChar);
}
out += phrase;
currentChar = phrase[0];
dictionary[code] = oldPhrase + currentChar;
code++;
oldPhrase = phrase;
}
return out;
} catch (error) {
throw new Error(error);
}
}