js实现集合

set是集合

集合是由一组无序且唯一(即不能重复)的项组成的。该数据结构使用了与有限集合相同的数学概念,但应用在计算机科学的数据结构中

构建set

 1 class set{
 2     constructor(){
 3         this.items = {}
 4     }
 5     has(element){
 6         return element in this.items
 7         // Object 原型有 hasOwnProperty 方法。该方法返回一个表明对象是否具有特定属性的布尔值
 8         // return Object.prototype.hasOwnProperty.call(this.items, element)
 9     }
10     add(element){
11         if (!this.has(element)) {
12             this.items[element] = element
13             return true
14         }
15         return false
16     }
17     delete(element){
18         if(this.has(element)){
19             delete this.items[element]
20             return true
21         }
22         return false
23     }
24     clear(){
25         this.items = {}
26     }
27     size(){
28         // JavaScript 的 Object 类有一个 keys 方法,它返回一个包含给定对象所有属性的数组
29         return Object.keys(this.items).length
30     }
31     values(){
32         // Object.values()方法返回了一个包含给定对象所有属性值的数组
33         return Object.values(this.items)
34     }
35     union(otherSet){
36         // 取当前集合和新集合的并集
37         const unionSet = new set()
38         this.values().forEach(value => unionSet.add(value))
39         otherSet.values().forEach(value => unionSet.add(value))
40         return unionSet
41     }
42     intersection(otherSet){
43         // 交集
44         const intersectionSet = new set()
45         const ownValue = this.values()
46         const otherValue = otherSet.values()
47         ownValue.forEach(value => {
48             if(value in otherValue){
49                 intersectionSet.add(value)
50             }
51         })
52         return intersectionSet
53     }
54     difference(otherSet){
55         // 差集,存在于当前集合但不存在于新集合中
56         const differenceSet = new set()
57         const ownValue = this.values()
58         const otherValue = otherSet.values()
59         ownValue.forEach(value => {
60             if(!(value in otherValue)){
61                 differenceSet.add(value)
62             }
63         })
64         return differenceSet
65     }
66     isSubsetOf(otherSet){
67         // 当前集合是否是其他集合的子集
68         if(this.size() > otherSet.size()){
69             return false
70         }
71         let isSubset = true     // 返回值
72         const ownValue = this.values()
73         const otherValue = otherSet.values()
74         ownValue.forEach(value => {
75             if(!(value in otherValue || this.size() === 0)){
76                 isSubset = false
77             }
78         })
79         return isSubset
80     }
81 }

 

posted @ 2021-08-04 15:44  邢韬  阅读(540)  评论(0编辑  收藏  举报