UNPKG

1.94 kBPlain TextView Raw
1export abstract class AbstractSet<T>{
2 public abstract add(item: T): this;
3 public abstract entries(): Array<T>;
4 public abstract remove(item: T): boolean;
5 public abstract has(item: T): boolean;
6 public abstract get Size(): number;
7
8 /**
9 * 获取左差集
10 * @param set
11 * @returns Array<T>
12 */
13 public diff(set: AbstractSet<T>){
14 if (!set){
15 return this.entries();
16 }
17 const items = this.entries();
18 const result: Array<T> = [];
19 for (const element of items) {
20 if (!set.has(element)){
21 result.push(element);
22 }
23 }
24 return result;
25 }
26
27 /**
28 * 获取并集
29 * @param set
30 * @returns Array<T>
31 */
32 public union(set: AbstractSet<T>){
33 if (!set){
34 return this.entries();
35 }
36 const items = set.entries();
37 const thisItems = this.entries();
38 for (const element of items) {
39 if (!this.has(element)){
40 thisItems.push(element);
41 }
42 }
43 return thisItems;
44 }
45
46 /**
47 * 获取交集
48 * @param set
49 * @returns Array<T>
50 */
51 public intersect(set: AbstractSet<T>){
52 if (!set){
53 return [];
54 }
55 const result: Array<T> = [];
56 let largeSet: AbstractSet<T>, smallItems: Array<T>;
57 if (this.Size > set.Size){
58 largeSet = this;
59 smallItems = set.entries();
60 }else{
61 largeSet = set;
62 smallItems = this.entries();
63 }
64 // 遍历大的集合取两个集合的交集
65 for (const element of smallItems) {
66 if (largeSet.has(element)){
67 result.push(element);
68 }
69 }
70 return result;
71 }
72
73 /**
74 * 判断是否为空集合
75 * @returns boolean
76 */
77 public isEmpty(){
78 return this.Size === 0;
79 }
80}