zoukankan      html  css  js  c++  java
  • 使用javaScript实现集合

    class Set{
        constructor(){
            this.items = {};
        }
        has(element){
           return Object.prototype.hasOwnProperty.call(this.items,element);
        }
        add(element){
            if(!this.has(element)){
                this.items[element] = element;
                return true;
            }
            return false;
        }
        delete(element){
            if(this.has(element)){
                delete this.items[element];
                return true;
            }
            return false;
        }
        clear(){
            this.items = {};
        }
        size(){
            return Object.keys(this.items).length;//ES6
        }
        values(){
            let values = [];
            for(let key in this.items){
                if(this.items.hasOwnProperty(key)){
                    values.push(key);
                }
            }
            return values;
        }
        //并集
        union(otherSet){
            const unionSet = new Set();
            this.values().forEach(value=>unionSet.add(value));
            otherSet.values().forEach(value => unionSet.add(value));
            return unionSet;
        }
        //交集
        intersection(otherSet){
            const intersection = new Set();
            let biggerSet = this.values();
            let smallerSet = otherSet.values();
            if(biggerSet.length < smallerSet.length){
                biggerSet = otherSet.values();
                smallerSet = this.values();
            }
            smallerSet.forEach(value=>{
                if(biggerSet.includes(value)){
                    intersection.add(value);
                }
            });
            return intersection;
        }
        //差集
        difference(otherSet){
            const differenceSet = new Set();
            this.values.forEach(value=>{
                if(!otherSet.includes(value)){
                    differenceSet.add(value);
                }
            });
            return differenceSet;
        }
        //子集
        isSubsetOf(otherSet){
            if(this.values.length<otherSet.length){
                return false;
            }
            let isSubset = true;
            otherSet.values().every(value=>{
                if(!this.values().includes(value)){
                    isSubset = false;
                    return false;
                }
                return true;
            });
            return isSubset;
        }
    }
  • 相关阅读:
    php 如何提升
    PHP判断客户端是否使用代理服务器及其匿名级别
    前端基础之BMO和DOM
    前端基础之JavaScript
    前端基础之CSS标签样式
    前端基础之CSS选择器
    前端基础之HTML标签
    面向对象之反射 元类
    面向对象之多态以及魔法函数
    面向对象之封装
  • 原文地址:https://www.cnblogs.com/MySweetheart/p/13223764.html
Copyright © 2011-2022 走看看