码迷,mamicode.com
首页 > Web开发 > 详细

JS实现集合

时间:2017-01-20 00:01:44      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:for   不能   move   ret   blog   values   this   span   sub   

集合是由一组无序且唯一(即不能重复)的项组成的。这个数据结构使用了与有限集合相同的数学概念,但应用在计算机科学的数据结构中。

 

function Set() {
    this.items = {};
}

Set.prototype = {
    constructer: Set,
    has: function(value) {
        return value in this.items;
    },
    add: function(value) {
        if (!this.has(value)) {
            this.items[value] = value;
            return true;
        }
        return false;
    },
    remove: function(value) {
        if (this.has(value)) {
            delete this.items[value];
            return true;
        }
        return false;
    },
    clear: function() {
        this.items = {};
    },
    size: function() {
        return Object.keys(this.items).length;
    },
    values: function() {
        return Object.keys(this.items); //values是数组
    },
    union: function(otherSet) {
        var unionSet = new Set();
        var values = this.values();
        for (var i = 0; i < values.length; i++) {
            unionSet.add(values[i]);
        }
        values = otherSet.values();
        for (var i = 0; i < values.length; i++) {
            unionSet.add(values[i]);
        }
        return unionSet;
    },
    intersection: function(otherSet) {
        var intersectionSet = new Set();
        var values = this.values();
        for (var i = 0; i < values.length; i++) {
            if (otherSet.has(values[i])) {
                intersectionSet.add(values[i]);
            }
        }
        return intersectionSet;
    },
    difference: function(otherSet) {
        var differenceSet = new Set();
        var values = otherSet.values();
        for (var i = 0; i < values.length; i++) {
            if (!this.has(values[i])) {
                differenceSet.add(values[i]);
            }
        }
        return differenceSet;
    },
    subset: function(otherSet) {
        if (this.size() > otherSet.size()) {
            return false;
        } else {
            var values = this.values();
            for (var i = 0; i < values.length; i++) {
                if (!otherSet.has(values[i])) {
                    return false;
                }
            }
        }
        return true;
    },
}

 

JS实现集合

标签:for   不能   move   ret   blog   values   this   span   sub   

原文地址:http://www.cnblogs.com/greatluoluo/p/6309010.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!