Is there a data structure like the Java Set in JavaScript? -
this question has answer here:
i want use data structure in javascript can used store number of ids. should able check if key exists in set, java sets.
i want achive same behaviours follows (this code in java):
set<string> st = new hashset<string>(); //add elemets if(st.contains("aks") ){ //do } i want javascript/dojo equivalent of above code.
i've written javascript hashset implementation want , allows object member of set: http://code.google.com/p/jshashtable
however, if need store strings, more storing set members property names of normal object. example:
function stringset() { var setobj = {}, val = {}; this.add = function(str) { setobj[str] = val; }; this.contains = function(str) { return setobj[str] === val; }; this.remove = function(str) { delete setobj[str]; }; this.values = function() { var values = []; (var in setobj) { if (setobj[i] === val) { values.push(i); } } return values; }; } a note implementation: val object used internally stringset implementation unique each set. comparing property values of object property names make set (setobj) against val eliminates need hasownproperty() check , guarantees strings have been added set show in values.
example usage:
var set = new stringset(); set.add("foo"); set.add("bar"); alert(set.contains("foo")); // true alert(set.contains("baz")); // false set.values(); // ["foo", "bar"], though not in order set.remove("foo"); set.values(); // ["bar"]
Comments
Post a Comment