JS 数据结构 集合(Set)

集合

  • 集合通常是由一组无序的,不能重复的元素组成
  • 特殊的数组
    1. 元素没有顺序,也不能重复
    2. 不能通过下标值进行访问,不能重复意味着相同的对象在集合中只会存在一份
class Set {
  constructor() {
    this.items = {}
  }

  /* 1. 添加新元素 */
  add(value) {
    // 1. 判断是否已经存在该元素
    if (this.has(value)) return false

    // 2. 将该元素添加到集合中
    this.items[value] = value
    return true
  }

  /* 2. 移出某个值 */
  remove(value) {
    // 1. 判断是否包含该元素
    if (!this.has(value)) return false

    // 2. 将该元素从集合中删除
    delete this.items[value]
    return true
  }

  /* 3. 检测某个值 */
  has(value) {
    return this.items.hasOwnProperty(value)
  }

  /* 4. 移除所有项 */
  clear() {
    this.items = {}
  }

  /* 5. 返回集合中元素的数量 */
  size() {
    return Object.keys(this.items).length
  }

  /* 6. 返回一个包含集合中所有值的数组 */
  values() {
    return Object.keys(this.items)
  }
}
集合间的操作

并集(所有元素)

union (otherSet) {
  /*
    this:    集合对象A;
    otherSet:集合对象B
   */

  // 1. 创建新的集合
  var unionSet = new Set()

  // 2. 将A集合中的所有元素放入新集合中
  var values = this.values()
  for (let i = 0; i < values.length; i++) {
    unionSet.add(values[i])
  }

  // 3. 取出B集合中的元素,判断是否需要添加到新集合中
  values = otherSet.values()
  for (let i = 0; i < values.length; i++) {
    unionSet.add(values[i])
  }

  // 4. 返回新数组
  return unionSet
}

交集(共有元素)

intersection (otherSet) {
  /* this:集合对象A;otherSet:集合对象B */

  // 1. 创建新的集合
  var intersectionSet = new Set()

  // 2. 将A集合中的所有元素放入新集合中
  var values = this.values()
  for (let i = 0; i < values.length; i++) {
    var item = values[i]
    if (otherSet.has(item)) {
      intersectionSet.add(item)
    }
  }

  // 3. 返回新数组
  return intersectionSet
}

差集(A-B)

difference (otherSet) {
  /* this:集合对象A;otherSet:集合对象B */

  // 1. 创建新的集合
  var differenceSet = new Set()

  // 2. 添加A中的元素到新集合
  var values = this.values()
  for (let i = 0; i < values.length; i++) {
    var item = values[i]
    if (!otherSet.has(item)) {
      differenceSet.add(item)
    }
  }

  // 3. 返回新集合
  return differenceSet
}

子集(A 包含 B)

subset (otherSet) {
  /* this:集合对象A;otherSet:集合对象B */

  // 1. 判断A中的元素是否是B中的元素
  var values = this.values()
  for (let i = 0; i < values.length; i++) {
    var item = values[i]
    if (!otherSet.has(item)) {
      return false
    }
  }

  // 2. 返回子集
  return true
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值