JavaScript实现集合Set

155 阅读1分钟

集合特点

  • 集合通常是由一组无序的不能重复的元素构成。

  • 数学中常指的集合和计算机中集合是同一个概念,集合的元素都是无序,不能重复的。

  • 集合是特殊的数组。

    • 特殊之处在于里面的元素没有顺序,也不能重复。
    • 没有顺序意味着不能通过下标值进行访问,不能重复意味着相同的对象在集合中只会存在一份。

封装集合

class mySet {
   //通过constructor判断是否数组,然后在里面执行
    constructor(iterator = []){
    //判断输入的数组是否是可迭代的对象
        if(typeof iterator[Symbol.iterator] !== 'function'){
        //返回错误
            throw new TypeError(`所输入的内容${iterator}不是可迭代的对象`);
        }
        数组储存数据
        this._datas = [];
        //直接调用add方法,遍历iterator
        for(const item of iterator){
            this.add(item);
        }
    }
    //长度,返回_datas的长度.length
    get size(){
        return this._datas.length;
    }
    //添加,一个参数,通过查找数组里的数据没有添加的数据,就往数组里添加
    add(data){
        if(!this.has(data)){
            this._datas.push(data);
        }
    }
    //查询,一个参数,调用 isEqual
    has(data){
        for(const item of this._datas){
            if(this.isEqual(data,item)){
                return true;
            }
        }
    }
    /判断是否为零,如果===0就返回true,不是就返回flase
    isEqual(data1 , data2){
        if(data1 === 0 && data2 === 0){
            return true;
        }
        return Object.is(data1 , data2);
    }
    //清空,将数组的长度归零
    clear(){
        this._datas.length = 0;
    }
     //删除处理,一个参数,通过循环_datas的长度,声明ele常量存储,然后遍历对于的数据,删除
    delete(data){
        for(let i = 0; i < this._datas.length;i++){
            const ele = this._datas[i];
            if(this.isEqual(data,ele)){
                this._datas.splice(i,1);
                return true;
            }
        }
        return false;
    }
    //方法重写,回调函数
    forEach(callback){
        for(const item of this._datas){
            callback(item , item , this);
        }
    }
    //方法迭代
    *[Symbol.iterator](){
        for(const item of this._datas){
            yield item;
        }
    }
}
let s = new mySet([5,25,5,14,12,142,14,14,12]);