集合

  1. function Set() {
  2. let items = {}; //用对象,因为一个键不能指向两个值,保证唯一性
  3. this.has = function(value) {
  4. return value in items;
  5. };
  6. //has更好的方式
  7. this.has = function(value) {
  8. return items.hasOwnProperty(value);
  9. };
  10. this.add = function(value){
  11. if(!this.has(value)){
  12. items[value] = value;
  13. return true;
  14. }
  15. return false;
  16. };
  17. this.remove = function(value) {
  18. if(this.has(value)) {
  19. delete items[value];
  20. return true;
  21. }
  22. return false;
  23. };
  24. this.clear = function(){
  25. items = {};
  26. };
  27. this.size = function() {
  28. return Object.keys(items).length;
  29. };
  30. this.values = function() {
  31. let values = [];
  32. for(let i = 0, keys = Object.keys(items); i < keys.length; i++){
  33. value.push(items[keys[i]]);
  34. }
  35. return values;
  36. };
  37. }

集合操作

并集

首先创建一个新的集合,代表两个集合的并集。然后获取第一个集合(当前Set类实例)所有的值,遍历并全部添加到代表并集的集合中,然后对第二个集合做同样的事。最后返回结果。

  1. this.union = function(otherSet) {
  2. let unionSet = new Set();
  3. let values = this.values();
  4. for(let i = 0; i<values.length; i++) {
  5. unionSet.add(values[i]);
  6. }
  7. values = otherSet.values();
  8. for(let i = 0; i<values.length; i++) {
  9. unionSet.add(values[i]);
  10. }
  11. return unionSet;
  12. };

交集

首先创建一个新的Set实例,这样就能用它返回共有的元素。接下来遍历当前Set实例所有的值,验证它们是否也存在于otherSet实例,然后如果这个值也存在于另一个Set实例中,就将其添加到创建的intersectionSet变量中。

  1. this.intersection = function(otherSet){
  2. let intersectionSet = new Set();
  3. let values = this.values();
  4. for(let i = 0; i<values.length; i++) {
  5. if(otherSet.has(values[i])){
  6. intersectionSet.add(values[i]);
  7. }
  8. }
  9. return intersectionSet
  10. }

差集

  1. this.difference = function(otherSet){
  2. let differenceSet = new Set();
  3. let values = this.values();
  4. for(let i = 0; i<values.length; i++) {
  5. if(!otherSet.has(values[i])){
  6. difference.add(values[i]);
  7. }
  8. }
  9. return differenceSet;
  10. }

子集

当前实例中的元素比otherSet实例更多,他就不是一个子集。然后遍历集合中所有元素,验证这些元素也存在于otherSet中。

  1. this.subset = function(otherSet){
  2. if(this.size() > otherSet.size()){
  3. return false;
  4. } else {
  5. let values = this.values();
  6. for(let i = 0; i<values.length; i++) {
  7. if(!otherSet.has(values[i])){
  8. return false;
  9. }
  10. }
  11. return true;
  12. }
  13. };