1 functionSet () {2 varitems={};3 4 This. has=function(value) {5 returnItems.hasownproperty (value);6 };7 8 This. add=function(value) {9 if(! This. has (value)) {Tenitems[value]=value; One return true; A } - return false; - }; the - This. remove=function(value) { - if( This. has (value)) { - DeleteItems[value]; + return true; - } + return false; A }; at - This. clear=function(){ -items={}; - }; - - //method One: ES5 above in /*this.size=function () { - return Object.keys (items). length; to }*/ + - //method Two: Compatible with the new strong the //hasOwnProperty () to exclude properties of the items prototype itself * This. size=function(){ $ varCount=0;Panax Notoginseng for(varPropinchitems) { - if(Items.hasownproperty (prop)) { thecount++; + } A } the returncount; + }; - $ //method One: ES5 above $ /*this.values=function () { - return Object.keys (items); - };*/ the - //compatibility is relatively strongWuyi This. values=function(){ the varkeys=[]; - for(varKeyinchitems) { Wu if(Items.hasownproperty (key)) { - Keys.push (key); About } $ } - returnkeys; - }; - A + //collection of and operations the This. union=function(otherset) { - varUnionset =NewSet (); $ varvalues= This. values (); the for(vari=0;i<values.length;i++){ the Unionset.add (Values[i]); the } the -values=otherset.values (); in for(i;i<values.length;i++){ the Unionset.add (Values[i]); the } About returnUnionset; the }; the the //intersection of sets + This. intersection=function(otherset) { - varIntersectionset =NewSet (); the varvalues= This. values ();Bayi for(vari=0;i<values.length;i++){ the if(Otherset.has (Values[i])) { the Intersectionset.add (Values[i]); - } - } the returnIntersectionset; the }; the the //Difference Set Operation - This. difference=function(otherset) { the varDifferenceset =NewSet (); the varvalues= This. values (); the for(vari=0;i<values.length;i++){94 if(!Otherset.has (Values[i])) { the Differenceset.add (Values[i]); the } the }98 returnDifferenceset; About }; - 101 //determine if it is a subset of Otherset102 This. subset=function(otherset) {103 if( This. Size () >otherset.size ()) {104 return false; the}Else{106 varvalues= This. values ();107 for(vari=0;i<values.length;i++){108 if(!Otherset.has (Values[i])) {109 return false; the }111 } the return true;113 } the the}
In this implementation, it is important to note that the set class is a set of mathematical concepts, and the elements in the collection must not be duplicated and unique. So using objects to initialize items, you can use the uniqueness of key-value pairs to achieve the nature of the set. The associated collection nature allows you to view knowledge of mathematical set concepts. The example above can be done by writing some simple HTML examples.
JavaScript data Structures-mimic similar set classes defined in ES6