2010-06-15 4 views

Répondre

45

Pour un ensemble de chaînes, j'utiliserais simplement un objet avec la valeur true.

var obj = {}; 
obj["foo"] = true; 
obj["bar"] = true; 

if(obj["foo"]) 
{ 
    // foo in set 
} 

Ceci est essentiellement comment fonctionne HashSet en Java, en supposant est mis en œuvre l'objet JavaScript comme Hashtable (ce qui est typique).

+0

Alors, comment retirer un objet de cet ensemble? obj ["foo"] = null? ou obj ["foo"] = faux? –

+8

@Eran, 'delete obj [" foo "]' ou 'delete obj.foo'. –

+0

Merci d'avoir enseigné à un vieux chien un nouveau truc :) c'est incroyable je ne l'ai jamais rencontré dans JS, ça me ramène à mes jours C++ quand même ... –

9

J'ai écrit une implémentation JavaScript d'un ensemble de hachage similaire à HashSet de Java. Il permet à n'importe quel objet (pas seulement les chaînes) d'être utilisé comme membre de l'ensemble. C'est basé sur les clés d'une table de hachage.

http://code.google.com/p/jshashtable/downloads/list

Documentation suivra peu de temps, je vous le promets. Pour l'instant, la source devrait vous donner l'API assez clairement, et voici un exemple:

var s = new HashSet(); 
var o1 = {name: "One"}, o2 = {name: "Two"}; 
s.add(o1); 
s.add(o2); 
s.add(o2); 
s.values(); // Array containing o1 and a single reference to o2 
1

Bien que cela semblait être un problème commun, et je l'ai trouvé ce qui semblait être a good Set class on the net qui prend en charge les objets, je voulais un plus simple et a fini par écrire un moi-même ... au cas où quelqu'un d'autre le trouve utile ...

/** 
* A Javascript Class that represents a set of unique values 
* 
* Usage: 
* 
* var s = new jsSet(); 
* 
* s.add('a1'); s.add('a2'); 
* 
* s.list(); >> ['a1','a2'] 
* 
* s.remove('a1'); s.list(); >> ['a2'] 
* 
* s.contains('a1') >> false 
* 
* s.contains('a2') >> true 
* 
* can be chained 
* s.add(null).add('hello'); 
* 
* add array 
* s.addAll([ null, 'a', 'b' ]); 
* 
* remove array 
* s.addAll([ null, 'a', 'b' ]); 
* 
* retrieve the elements as a list 
* s.list(); 
* 
* size of the set 
* s.size(); 
* 
*/ 
function jsSet() { 

    // null can also be an element of the set, but needs 
    // a separate indication to differentiate it from 
    // the string "null" as well 
    this.isNullAdded = false; 

    // private member variable hence no 'this' 
    var map = {}; 

    // Scope for optimization 
    // could be cached instead of generating each time 
    // this.uniqueList = []; 

    // returns true if the element is in this set, false otherwise 
    this.contains = function(key) { 

     if (key === null) 
      return this.isNullAdded; 
     else if (key === undefined) 
      return false; 
     else 
      return map[key] ? true : false; 
    }; 

    // adds the element to the set 
    this.add = function(val) { 

     if (val === null) 
      this.isNullAdded = true; 
     else if (val !== undefined) 
      map[val] = true; 
     return this; 
    }; 

    // adds all the elements of the array to the set 
    this.addAll = function(val) { 

     if (val !== null && val !== undefined && val instanceof Array) { 
      for (var idx = 0; idx < val.length; idx++) { 
       this.add(val[idx]); 
      } 
     } 
     return this; 
    }; 

    // removes the specified element from the set 
    this.remove = function(val) { 
     if (val === null) 
      this.isNullAdded = false; 
     else if (val !== undefined) 
      delete map[val]; 
     return this; 
    }; 

    // removes all the element in the array from the set 
    this.removeAll = function(val) { 

     if (val !== null && val !== undefined && val instanceof Array) { 
      for (var idx = 0; idx < val.length; idx++) { 
       console.log('val: %s:%s', idx, val[idx]); 
       this.remove(val[idx]); 
      } 
     } 
     return this; 
    }; 

    // empties the set of all values 
    this.clear = function() { 

     this.isNullAdded = false; 
     map = {}; 
     return this; 
    }; 

    // returns the number of elements in the set 
    this.size = function() { 

     return this.list().length; 
    }; 

    // returns true if the set is empty, false otherwise 
    this.isEmpty = function() { 

     return this.list().length > 0? false: true; 
    }; 

    // returns the elements of the set as a list 
    this.list = function() { 
     var arr = []; 

     if (this.isNullAdded) 
      arr.push(null); 

     for (o in map) { 
      // protect from inherited properties such as 
      // Object.prototype.test = 'inherited property'; 
      if (map.hasOwnProperty(o)) 
       arr.push(o); 
     } 
     return arr; 
    }; 
}; 
+0

si nous n'avons pas besoin de valeurs nulles dans l'ensemble, alors nous pouvons simplement faire une suppression (null) après avoir ajouté tous les éléments. – msanjay

Questions connexes