Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现一个 Set 的 polyfill #60

Open
lovelmh13 opened this issue May 30, 2021 · 0 comments
Open

实现一个 Set 的 polyfill #60

lovelmh13 opened this issue May 30, 2021 · 0 comments

Comments

@lovelmh13
Copy link
Owner

const MySet = function (iterator) {
  this._value = []
  this.size = 0

  init = () => {
    if (iterator[Symbol.iterator]) {
      for (const [index, item] of iterator.entries()) {
        this.add(item)
      }
    } else {
      throw new TypeError(
        `${typeof iterator} is not iterable (cannot read property Symbol(Symbol.iterator))`
      )
    }
  }

  init()
}

MySet.prototype.add = function (value) {
  if (this._value.indexOf(value) === -1) {
    // 保证了唯一性
    this._value.push(value)
    this.size++
  }
  return this // 返回 this 本身
}

MySet.prototype.has = function (value) {
  return this._value.indexOf(value) !== -1
}

MySet.prototype.delete = function (value) {
  const index = this._value.indexOf(value)
  if (index !== -1) {
    this._value.splice(index, 1)
    this.size--
    return true
  } else {
    return false
  }
}

// 还有一些方法,暂时没有实现

// -------------- 测试 --------------
const bar = ['a', 'b', 'c', 'd']
const bar1 = ['a1', 'b1', 'c1', 'd1']

const res1 = new MySet(bar)
console.log(res1)

// const res2 = new MySet(bar1)
// res2.add('e1')
// console.log('res2: ', res2)
// console.log('res1: ', res1)
res1.delete('c')
console.log(res1)

// https://juejin.cn/post/6844903639962632200#heading-0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant