1 | const sortKeysByLength = dict => dict.sort(([a], [b]) => String(b).length - String(a).length);
|
2 |
|
3 | const makeReplaceable = function (dict) {
|
4 | if (this !== null && this !== void 0 && this.sort) sortKeysByLength(dict);
|
5 | Object.defineProperty(dict, Symbol.replace, {
|
6 | value(word, after) {
|
7 | for (let [curr, proj] of this) word = word.replace(curr, proj);
|
8 |
|
9 | return after ? after(word) : word;
|
10 | },
|
11 |
|
12 | configurable: true,
|
13 | enumerable: false
|
14 | });
|
15 | return dict;
|
16 | };
|
17 | const MakeReplaceable = ({
|
18 | sort = true
|
19 | } = {}) => makeReplaceable.bind({
|
20 | sort
|
21 | });
|
22 |
|
23 | const translate = (word, dict) => {
|
24 | for (let [curr, proj] of dict) word = word.replace(curr, proj);
|
25 |
|
26 | return word.trim();
|
27 | };
|
28 |
|
29 | class Translator {
|
30 | constructor(dictionary) {
|
31 | var _dictionary;
|
32 |
|
33 | this.dict = (_dictionary = dictionary, makeReplaceable(_dictionary));
|
34 | }
|
35 |
|
36 | static build(dict, {
|
37 | sort = true
|
38 | } = {}) {
|
39 | var _dict;
|
40 |
|
41 | if (sort) _dict = dict, sortKeysByLength(_dict);
|
42 | return new Translator(dict);
|
43 | }
|
44 |
|
45 | parse(word, after) {
|
46 | return word.replace(this.dict, after);
|
47 | }
|
48 |
|
49 | reboot(dict) {
|
50 | var _dict2;
|
51 |
|
52 | return dict ? (this.dict = (_dict2 = dict, makeReplaceable(_dict2)), this) : this;
|
53 | }
|
54 |
|
55 | }
|
56 |
|
57 | export { MakeReplaceable, Translator, makeReplaceable, translate };
|