Blame view

lib/jsdom/living/helpers/ordered-set.js 2.04 KB
858f2bdf5   Boyan Georgiev   fixes
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
  "use strict";
  
  // https://infra.spec.whatwg.org/#sets
  //
  // Only use this class if a Set cannot be used, e.g. when "replace" operation is needed, since there's no way to replace
  // an element while keep the relative order using a Set, only remove and then add something at the end.
  
  module.exports = class OrderedSet {
    constructor() {
      this._items = [];
    }
  
    append(item) {
      if (!this.contains(item)) {
        this._items.push(item);
      }
    }
  
    prepend(item) {
      if (!this.contains(item)) {
        this._items.unshift(item);
      }
    }
  
    replace(item, replacement) {
      let seen = false;
      for (let i = 0; i < this._items.length;) {
        const isInstance = this._items[i] === item || this._items[i] === replacement;
        if (seen && isInstance) {
          this._items.splice(i, 1);
        } else {
          if (isInstance) {
            this._items[i] = replacement;
            seen = true;
          }
          i++;
        }
      }
    }
  
    remove(...items) {
      this.removePredicate(item => items.includes(item));
    }
  
    removePredicate(predicate) {
      for (let i = 0; i < this._items.length;) {
        if (predicate(this._items[i])) {
          this._items.splice(i, 1);
        } else {
          i++;
        }
      }
    }
  
    empty() {
      this._items.length = 0;
    }
  
    contains(item) {
      return this._items.includes(item);
    }
  
    get size() {
      return this._items.length;
    }
  
    isEmpty() {
      return this._items.length === 0;
    }
  
    // Useful for other parts of jsdom
  
    [Symbol.iterator]() {
      return this._items[Symbol.iterator]();
    }
  
    keys() {
      return this._items.keys();
    }
  
    get(index) {
      return this._items[index];
    }
  
    some(func) {
      return this._items.some(func);
    }
  
    // https://dom.spec.whatwg.org/#concept-ordered-set-parser
    static parse(input) {
      const tokens = new OrderedSet();
      for (const token of input.split(/[\t
  \f\r ]+/)) {
        if (token) {
          tokens.append(token);
        }
      }
      return tokens;
    }
  
    // https://dom.spec.whatwg.org/#concept-ordered-set-serializer
    serialize() {
      return this._items.join(" ");
    }
  };