2010-06-15 7 views

Antwort

45

Für eine Reihe von Strings würde ich nur ein Objekt mit dem Wert True verwenden.

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

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

Dies ist im Grunde, wie HashSet in Java funktioniert, vorausgesetzt, das JavaScript-Objekt als Hash-Tabelle implementiert ist (was typisch ist).

+0

So, wie man ein Objekt von diesem Satz entfernt? obj ["foo"] = null? oder obj ["foo"] = falsch? –

+8

@Eran, 'lösche obj [" foo "]' oder 'lösche obj.foo'. –

+0

Danke, dass du einem alten Hund einen neuen Trick beigebracht hast :) das ist erstaunlich, ich habe es nie in JS gesehen, bringt mich aber zurück zu meinen C++ - Tagen ... –

9

Ich habe eine JavaScript-Implementierung eines Hash-Sets geschrieben, das dem HashSet von Java ähnelt. Es erlaubt jedem Objekt (nicht nur Strings) als Set-Member verwendet zu werden. Es basiert auf den Schlüsseln einer Hash-Tabelle.

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

Dokumentation in Kürze folgen, das verspreche ich. Vorerst sollte die Quelle Sie die API ziemlich klar geben, und hier ist ein Beispiel:

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

Nun wäre es ein weit verbreitetes Problem zu sein schien, und ich fand, wie es schien a good Set class on the net zu sein, die Objekte unterstützt, wollte ich ein Einfacher und endete Schreiben eines selbst ... falls jemand anderes es nützlich findet ...

/** 
* 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

Wenn wir im Set keine Null-Werte benötigen, können wir nach dem Hinzufügen aller Elemente einfach ein Entfernen (Null) durchführen. – msanjay

Verwandte Themen