集合是由一組無(wú)序且唯一的項(xiàng)組成的:
集合可以進(jìn)行 并集、交集、差集、子集操作。
集合的代碼實(shí)現(xiàn):
function Set() {
? ? var items = {};
? ? this.add = function(value) {
? ? ? ? if(!this.has(value)) {
? ? ? ? ? ? items[value] = value;
? ? ? ? ? ? return true;
? ? ? ? }else {
? ? ? ? ? ? return false;
? ? ? ? }
? ? }
? ? this.remove = function(value) {
? ? ? ? if(this.has(value)) {
? ? ? ? ? ? delete items[value];
? ? ? ? ? ? return true;
? ? ? ? }else {
? ? ? ? ? ? return false;
? ? ? ? }
? ? }
? ? this.has = function(value) {
? ? ? ? return value in items;
? ? }
? ? this.clear = function() {
? ? ? ? this.items = {};
? ? }
? ? this.size = function() {
? ? ? ? return Object.keys(items).length;
? ? }
? ? this.values = function() {
? ? ? ? var keys = [];
? ? ? ? for(let key in items) {
? ? ? ? ? ? keys.push(key);
? ? ? ? }
? ? ? ? return keys;
? ? }
? ? this.union = function(otherSet) {
? ? ? ? var unionSet = new Set();
? ? ? ? let values = this.values();
? ? ? ? for(let i=0;i<values.length;i++) {
? ? ? ? ? ? unionSet.add(values[i]);
? ? ? ? }
? ? ? ? values = otherSet.values();
? ? ? ? for(let i=0; i< values.length; i++) {
? ? ? ? ? ? unionSet.add(values[i]);
? ? ? ? }
? ? ? ? return unionSet;
? ? }
? ? this.intersection = function(otherSet) {
? ? ? ? var intersection = new Set();
? ? ? ? let values = this.values();
? ? ? ? for(let i=0; i< values.length; i++) {
? ? ? ? ? ? if(otherSet.has(values[i])) {
? ? ? ? ? ? ? ? intersection.add(values[i]);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return intersection;
? ? }
? ? this.difference = function(otherSet) {
? ? ? ? const difference = new Set();
? ? ? ? let values = this.values();
? ? ? ? for(let i=0; i< values.length; i++) {
? ? ? ? ? ? if(!otherSet.has(values[i])) {
? ? ? ? ? ? ? ? difference.add(values[i]);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return difference;
? ? }
? ? this.subset = function(otherSet) {
? ? ? ? if(this.size() > otherSet.size()) {
? ? ? ? ? ? return false;
? ? ? ? }else{
? ? ? ? ? ? const values = this.values();
? ? ? ? ? ? for(let i=0; i< values.length; i++) {
? ? ? ? ? ? ? ? if(!otherSet.has(values[i])) {
? ? ? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? return true;
? ? ? ? }
? ? }
}
const set = new Set();
set.add("aa");
set.add("aa");
set.add("bb");
set.add("ee");
console.log(set.values()); // ['aa', 'bb',? 'ee']
console.log(set.size()); // 2
console.log(set.remove('dd')); // false
set.remove("aa");
console.log(set.values()); // ['bb, 'ee']
const set1 = new Set();
set1.add("bb");
set1.add("ff");
set1.add("gg");
console.log(set.union(set1).values()); // [ 'bb', 'ee', 'ff', 'gg' ]
console.log(set.intersection(set1).values()); // [ 'bb' ]
console.log(set.difference(set1).values()); // ['ee']
console.log(set.subset(set1)); // false