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

集合 #15

Open
bWhirring opened this issue Apr 26, 2020 · 0 comments
Open

集合 #15

bWhirring opened this issue Apr 26, 2020 · 0 comments
Labels
easy easy

Comments

@bWhirring
Copy link
Owner

class Set<T> {
  private items: any

  constructor() {
    this.items = {}
  }

  add(element: T) {
    if (!this.has(element)) {
      this.items[element] = element
      return true
    }

    return false
  }

  has(element: T) {
    return Object.prototype.hasOwnProperty.call(this.items, element)
  }

  remove(element: T) {
    if (this.has(element)) {
      delete this.items[element]
      return true
    }
    return false
  }

  size() {
    return Object.keys(this.items).length
  }

  clear() {
    this.items = {}
  }

  values() {
    return Object.keys(this.items)
  }

  union(otherSet: Set<T>) {
    const set = new Set()

    this.values().forEach(value => set.add(value))
    otherSet.values().forEach(value => set.add(value))

    return set
  }

  interSection(otherSet: Set<T>) {
    const set = new Set()


    const values = this.values()
    const otherValues = otherSet.values()

    let biggerSet = values;
    let smallerSet = otherValues;

    if (values.length < otherValues.length) {
      smallerSet = values
      biggerSet = otherValues
    }

    smallerSet.forEach(v => {
      if (biggerSet.includes(v)) set.add(v)
    })
    return set
  }

  isSubsetOf(otherSet: Set<T>) {
    if (this.size() > otherSet.size()) {
      return false;
    }

    let isSubset = true;
    this.values().every((value: any) => {
      if (!otherSet.has(value)) {
        isSubset = false;
        return false;
      }
      return true;
    });

    return isSubset;
  }

  difference(otherSet: Set<T>) {
    const set = new Set()

    this.values().forEach((value: any) => {
      if (!otherSet.has(value)) set.add(value)
    })
    return set
  }

}
@bWhirring bWhirring added the easy easy label Apr 26, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
easy easy
Projects
None yet
Development

No branches or pull requests

1 participant