aboutsummaryrefslogtreecommitdiff
path: root/src/js/fiveui/js/set.js
blob: 7015a3ed3e6059e4e25be03490a82705d9969988 (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


(function() {

Set = function() {
  this.elems = {};
};

_.extend(Set.prototype, {

  add: function(obj) {
    var hash = this._getHash(obj);
    if(this.elems[hash] == undefined) {
      this.elems[hash] = obj;
    }
  },

  remove: function(obj) {
    var hash = this._getHash(obj);
    if(this.elems[hash]) {
      delete this.elems[hash];
    }
  },

  member: function(obj) {
    var hash = this._getHash(obj);
    return !!this.elems[hash];
  },

  contains: function(obj) {
    return this.member(obj);
  },

  size: function () {
    return _.size(this.elems);
  },

  isEmpty: function() {
    return this.size() == 0;
  },

  each: function(k, cxt) {
    _.each(this.elems, k, cxt);
  },

  _getHash: function(obj) {
    var str = obj.toString();

    // the same hash function that java uses for String.hashCode
    return _.reduce(str, function(hash, c) {
      hash = ((hash << 5) - hash) + c.charCodeAt();
      return hash & hash;
    }, 0);
  }

});

})();