Set源码及其详细解析
class MySet {
constructor(iterator = []) {
if (typeof iterator[Symbol.iterator] != "function") {
throw new TypeError(`您所提供的${iterator}不是可迭代对象`)
}
this._datas = []
for (const item of iterator) {
this.add(item)
}
}
add(data) {
if (!this.has(data)) {
this._datas.push(data)
}
}
has(data) {
for (const item of this._datas) {
if (this.isEqual(data, item)) {
return true
}
}
return false
}
isEqual(data1, data2) {
if (data1 == 0 && data2 == 0) {
return true
}
return Object.is(data1, data2)
}
get size() {
return this._datas.length
}
delete(data) {
for (let i = 0; i < this._datas.length; i++) {
const ele = this._datas[i]
if (this.isEqual(ele, data)) {
this._datas.splice(i, 1)
return true
}
}
return false
}
clear() {
this._datas.length = 0;
}
forEach(callback) {
for (let item of this._datas) {
callback(item, item, this)
}
}
*[Symbol.iterator]() {
for (const item of this._datas) {
yield item;
}
}
}