集合的特点
1.无序
2.唯一性
3.不可重复
集合相对于前面几种数据结构,比较简单好理解,看看代码实现就能知道他的用法了
集合的创建
function MySet() {
this.item = {};
}
MySet.prototype.has = function (value) {
return value in this.item;
};
//增
MySet.prototype.add = function (value) {
if (this.has(value)) return false;
this.item[value] = value;
return true;
};
//删
MySet.prototype.remove = function (value) {
if (!this.has(value)) return false;
delete this.item[value];
return true;
};
//清空
MySet.prototype.clear = function () {
this.item = {};
};
//长度
MySet.prototype.size = function () {
return Object.keys(this.item).length;
};
//获取值
MySet.prototype.values = function () {
let arr = [];
console.log("🚀 ~ Object.keys(this.item):", Object.keys(this.item));
for (i = 0; i < Object.keys(this.item).length; i++) {
const key = Object.keys(this.item)[i];
arr.push(this.item[key]);
}
return arr;
};
//查询
MySet.prototype.print = function () {
console.log(this.item);
return this.item;
};
//集合的操作
//求并集
MySet.prototype.addUnion = function (data) {
let newSet = new MySet();
let values = this.values();
for (let i = 0; i < values.length; i++) {
newSet.add(values[i]);
}
let values2 = data.values();
for (let i = 0; i < values2.length; i++) {
newSet.add(values2[i]);
}
return newSet.values();
};
//求交集
MySet.prototype.interSection = function (data) {
const interSection = new MySet();
const oldValues = this.values();
for (let i = 0; i < oldValues.length; i++) {
if (data.has(oldValues[i])) {
interSection.add(oldValues[i]);
}
}
return interSection.values();
};
//求差集
MySet.prototype.diff = function (data) {
const diff = new MySet();
const oldValues = this.values();
for (let i = 0; i < oldValues.length; i++) {
if (!data.has(oldValues[i])) {
diff.add(oldValues[i]);
}
}
return diff.values();
};
测试
const set = new MySet()
set.add('a',1)
set.add('b',2)
console.log(set.print())
console.log('values',set.values())
//测试求并集
const set1 = new MySet()
set1.add(1)
set1.add(2)
set1.add(3)
const set2 = new MySet()
set2.add(3)
set2.add(4)
set2.add(5)
set2.add(6)
set2.add(7)
const result = set1.addUnion(set2)
console.log(result) //[1, 2, 3, 4, 5, 6, 7]
//求交集
const set3 = new MySet()
set3.add(1)
set3.add(2)
set3.add(3)
const set4 = new MySet()
set4.add(3)
set4.add(4)
set4.add(5)
set4.add(6)
const result2 = set3.interSection(set4)
console.log("🚀 ~ result2:", result2)
//求差集
const set5 = new MySet()
set5.add(1)
set5.add(2)
set5.add(3)
const set6 = new MySet()
set6.add(3)
set6.add(4)
const result3 = set5.diff(set6)
console.log("🚀 ~ result3:", result3)
可以参照着练习下,其实不难,这个知识点!!