原生js实现类Set结构

使用原生js,实现类Set结构的类

主要实现的方法

add(value):向集合添加一个新的项。

remove(value):从集合移除一个值。

has(value):如果值在集合中,返回true,否则返回false。

clear():移除集合中的所有项。

size():返回集合所包含元素的数量。与数组的length属性类似。

values():返回一个包含集合中所有值的数组。

has(value)方法

this.has = function(value){
    return items.hasOwnProperty(value);
};

add方法

1
2
3
4
5
6
7
this.add = function(value){
if (!this.has(value)){
items[value] = value;
return true;
}
return false;
};

remove和clear方法

1
2
3
4
5
6
7
8
9
10
11
this.remove = function(value){
if (this.has(value)){
delete items[value];
return true;
}
return false;
};
this.clear = function(){
items = {};
};

size方法

1
2
3
this.size = function(){
return Object.keys(items).length;
};

values方法

1
2
3
this.values = function(){
return Object.keys(items);
};

参考资料 《学习JavaScript数据结构与算法》

显示 Gitment 评论