这个俗人 2022-05-04 13:44:27
3.5 集合
由一个或多个元素所构成的叫做集合(Set)。若x是集合A的元素,则记作x∈A。集合中的元素有三个特征:1.确定性(集合中的元素必须是确定的) 2.互异性(集合中的元素互不相同。例如:集合A={1,a},则a不能等于1) 3.无序性(集合中的元素没有先后之分。)
ES6已经有Set
了,想了解的可以参考ECMAScript 6 入门:Set
但基于理解Set特性,这里仍旧给出Set的一个实现:
const getName = Symbol('getName') class Set { constructor(array) { this.map = {} if (Array.isArray(array)) { array.forEach(v => this.map[this[getName](v)] = v) } } [getName](value) { return Object.prototype.toString.call(value) + value } has(value, name) { return this.map.hasOwnProperty(name || this[getName](value)) } add(value) { const name = this[getName](value) if (this.has(value, name)) { return false } this.map[name] = value return true } delete(value) { const name = this[getName](value) if (this.has(value, name)) { delete this.map[name] return true } return false } values() { return Object.keys(this.map).map(key => this.map[key])[Symbol.iterator]() } entries() { return Object.keys(this.map).map(key => [this.map[key], this.map[key]])[Symbol.iterator]() } size() { return Object.keys(this.map).length } clear() { this.map = {} } } Set.prototype[Symbol.iterator] = Set.prototype.keys = Set.prototype.values // 并集 Set.union = function(set1, set2) { if (Array.isArray(set1)) set1 = new Set(set1) if (Array.isArray(set2)) set2 = new Set(set2) const res = new Set() if (set1 instanceof Set && set2 instanceof Set) { for (let item of set1) { res.add(item) } for (let item of set2) { res.add(item) } } return res } // 交集 Set.intersect = function(set1, set2) { if (Array.isArray(set1)) set1 = new Set(set1) if (Array.isArray(set2)) set2 = new Set(set2) const res = new Set() if (set1 instanceof Set && set2 instanceof Set) { for (let item of set1) { if (set2.has(item)) { res.add(item) } } } return res } // 差集 Set.diff = function(set1, set2) { if (Array.isArray(set1)) set1 = new Set(set1) if (Array.isArray(set2)) set2 = new Set(set2) const res = new Set() if (set1 instanceof Set && set2 instanceof Set) { const intersection = Set.intersect(set1, set2) for (let item of set1) { if (!intersection.has(item)) { res.add(item) } } for (let item of set2) { if (!intersection.has(item)) { res.add(item) } } } return res }
- 共 1 页
- 1
第 105 题:编程题 匹配查找特定字符串