summaryrefslogtreecommitdiff
path: root/node_modules/html-minifier-terser/src/tokenchain.js
blob: 6bba3bf8daa0028d2d51a8e87f8e9d24ff8010a0 (plain)
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
class Sorter {
  sort(tokens, fromIndex = 0) {
    for (let i = 0, len = this.keys.length; i < len; i++) {
      const key = this.keys[i];
      const token = key.slice(1);

      let index = tokens.indexOf(token, fromIndex);

      if (index !== -1) {
        do {
          if (index !== fromIndex) {
            tokens.splice(index, 1);
            tokens.splice(fromIndex, 0, token);
          }
          fromIndex++;
        } while ((index = tokens.indexOf(token, fromIndex)) !== -1);

        return this[key].sort(tokens, fromIndex);
      }
    }
    return tokens;
  }
}

class TokenChain {
  add(tokens) {
    tokens.forEach((token) => {
      const key = '$' + token;
      if (!this[key]) {
        this[key] = [];
        this[key].processed = 0;
      }
      this[key].push(tokens);
    });
  }

  createSorter() {
    const sorter = new Sorter();

    sorter.keys = Object.keys(this).sort((j, k) => {
      const m = this[j].length;
      const n = this[k].length;
      return m < n ? 1 : m > n ? -1 : j < k ? -1 : j > k ? 1 : 0;
    }).filter((key) => {
      if (this[key].processed < this[key].length) {
        const token = key.slice(1);
        const chain = new TokenChain();

        this[key].forEach((tokens) => {
          let index;
          while ((index = tokens.indexOf(token)) !== -1) {
            tokens.splice(index, 1);
          }
          tokens.forEach((token) => {
            this['$' + token].processed++;
          });
          chain.add(tokens.slice(0));
        });
        sorter[key] = chain.createSorter();
        return true;
      }
      return false;
    });
    return sorter;
  }
}

export default TokenChain;