I've read the solutions and I tried some. After trying to use the object[key]
method I realized that it wasn't going to work. I wanted a HashSet that could store HTML elements. When adding these objects the key
was translated to a string, so I came up with my own set based on jQuery. It supports add
, remove
, contains
and clear
.
var HashSet = function () {
var set = [];
this.add = function (obj) {
if (!this.contains(obj)) {
set.push(obj);
}
};
this.remove = function (obj) {
set = jQuery.grep(set, function (value) {
return value !== obj;
});
};
this.clear = function () {
set = [];
};
this.contains = function (obj) {
return $.inArray(obj, set) > -1;
};
this.isEmpty = function () {
return set.length === 0;
};
};
Note
When adding something like $('#myElement')
to the set, one should add the real HTML element $('#myElement')[0]
. Oh... and if you want to keep a list of changed controls - use the name of the element (gave me a problem with :radio
controls).
Note2
I think the object[key]
might be faster for your integers.
Note3
If you are only going to store numbers or string, this set will be faster:
var HashSet = function () {
var set = {};
this.add = function (key) {
set[key] = true;
};
this.remove = function (key) {
delete set[key];
};
this.clear = function () {
set = {};
};
this.contains = function (key) {
return set.hasOwnProperty(key);
};
this.isEmpty = function () {
return jQuery.isEmptyObject(set);
};
};