Native JS achieve collection structure

1 Introduction

Set is a set of unordered and only (i.e. not duplicate) items thereof. You can think of an array of collections neither duplicate elements, there is no concept of order. In ES6 it has built a collection of this data structure - Set. Next, we use native JS to implement this data structure.

2. Create collections

First, let's create a collection class, and declare some examples of its method, as follows:

class Set {
  constructor() {
    this.items = {}
  }
  
  has(value) {}
  add(value) {}
  remove(value) {}
  clear() {}
  size() {}
  values() {}
  union(otherSet) {}
  intersection(otherSet) {}
  difference(otherSet){}
  isSubset(otherSet){}  
}

In the above code, we use the object instead of an array to represent the set ( items), because the elements of the collection are unique, and the JavaScriptobject does not allow a key point to two different attributes, just to meet a collection of this nature. After creating Setthe class, we declare some of its methods:

  • add (value): add a new item to the collection.
  • remove (value): delete a value from the set.
  • has (value): determines whether there is a value in the collection, return true, otherwise false.
  • clear (): Empty collection.
  • size (): returns the set number of elements contained.
  • values (): returns an array comprising a set of all the values.
  • union (otherSet): find the current set of a given set otherSetand set.
  • intersection (otherSet): find the current set with a given set of otherSetintersections.
  • difference (otherSet): find the current set of a given set of otherSetdifference sets.
  • isSubset (otherSet): determines whether or not the current set to a given set of otherSetsubsets.

3. The method implementation

3.1 has(value)

We must first realize that has(value)method. This is because it will be called by other methods. The method used to determine whether a value is present in the collection, return true, otherwise false. as follows:

// 判断value是否存在于集合内,返回true或false
has(value) {
    return this.items.hasOwnProperty(value)
}

We will meet all elements itemsare stored in the following manner:

this.items = {
    '元素1':'元素1',
    '元素2':'元素3',
    '元素3':'元素3',
    //...
}

Let each of us within objects keyand valueare equal, it represents an element. When we need to determine whether there is a value in the collection, we need only determine whether the value of the property to the object, so we can directly call the hasOwnPropertymethod.

3.2 add(value)

The method used to add a new entry into the collection, to achieve the following:

// 向集合内添加一个数据,成功返回true,失败返回false
add(value) {
    if (this.has(value)) {
        return false
    }
    this.items[value] = value
    return true
}

Because it does not allow duplicate elements within the set, so before adding first determine whether you want to add elements already present in the collection, if it exists, is returned false, not to add. Otherwise, a new element is added by way of assignment objects within the collection.

3.3 remove(value)

The method is used to remove a value from the set. To achieve the following:

// 从集合内删除一个数据
remove(value) {
    if (this.has(value)) {
        delete this.items[value]
        return true;
    }
    return false;
}

Analyzing before deleting elements to be deleted exists in the set, if present, would remove itself using object properties way to remove the element from the set, and finally returns true. If not, return false.

3.4 size()

The method used to obtain the number of elements in a set. To achieve the following:

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

ObjectClass has a keysmethod that returns an array of all the properties of the given object to contain. We can use this array lengthto get the property to itemsthe number of attributes of the object.

3.5 values()

The method for obtaining a collection of all values ​​of the array contained. To achieve the following:

// 以数组形式返回集合内的所有元素
values() {
    return Object.keys(this.items)
}

The same size()way to achieve the same, Object.keysthe method returns an array of all attributes of a given object contains.

3.6 clear()

This method is used to empty the collection, which removes all elements in the set. To achieve the following:

// 清空集合
clear() {
    this.items = {}
}

Empty the collection, which is to this.itmesbecome an empty object, then we will empty object directly {}assigned to the this.itemscan.

3.7 union(otherSet)

The current method used to find the set of a given set otherSetof union .

And mathematical concepts set is the set A and set B and set, expressed as:
\ [A \ B Cup \]

The set defined as follows:
\ [A \ Cup B = \ {X | X \ in A \ VEE X \ in B \} \]
mean x(element) present in the Amedium, or xis present in the Bmiddle. The following figure shows the union operation:

To achieve the following:

  // 求并集
  union(otherSet) {
    let unionSet = new Set()     // 创建一个新的集合,用于存储两个集合的并集
    let values = this.values();  //获取第一个集合(当前的Set类实例)所有的值
    for (let i = 0; i < values.length; i++) {  // 遍历并全部添加到代表并集的集合中
      unionSet.add(values[i]);
    }
    values = otherSet.values(); // 第二个集合同理
    for (let i = 0; i < values.length; i++) {
      unionSet.add(values[i]);
    }
    return unionSet;
  }

First you need to create a new collection, representing the union of the two sets. Next, the first obtaining a collection of all of the values ​​(current Set class instances), and traversing and represents a collection of all added to the set. Then the second set to do the same thing. Finally, return the results.

3.8 intersection(otherSet)

The current method used to find the set of a given set otherSetof intersection .

Mathematical concepts intersection of the set A and the set intersection B, expressed as:
\ [A \ CAP B \]
The set defined as follows:
\ [A \ CAP B = \ {X | X \ in A \ Wedge X \ in B \} \]
mean x(element) in the present A, and the xpresent in the Bmiddle. The following figure shows the intersection operation:

To achieve the following:

// 求交集
  intersection(otherSet) {
    let intersectionSet = new Set()      // 创建一个新的集合,用于存储两个集合的交集结果
    let values = this.values();
    for (let i = 0; i < values.length; i++) {  // 遍历当前的集合中的元素,如果这个元素也存在与otherSet,则将该元素存入intersectionSet
      if (otherSet.has(values[i])) {
        intersectionSet.add(values[i])
      }
    }
    return intersectionSet
  }

First you need to create a new collection intersectionSet, representing the intersection of two sets. Next, obtain a first set (Set current class instance) all values, through and determines whether each element is present in the set otherSet, if present, it indicates that the element is present both in the first set, and present in the second sets otherSet, add it to the collection on behalf of the intersection intersectionSetin. Finally, return the results.

3.9 difference(otherSet)

The current method used to find the set of a given set otherSetof set difference .

Mathematical concepts difference set is the set Aand the set Bof difference set, expressed as:
\ [A - B \]
is defined as follows:
\ [A - B = \ {X | X \ in A \ Wedge X \ notin B \} \]
means x(element) present in the Amedium, and is xnot present in the Bmedium. The following figure shows the set Aand Bthe set difference operation:

To achieve the following:

// 求差集
  difference(otherSet){
    let differenceSet = new Set()      // 创建一个新的集合,用于存储两个集合的交集结果
    let values = this.values();
    for (let i = 0; i < values.length; i++) {  // 遍历当前的集合中的元素,如果这个元素不存在于otherSet中,则将该元素存入differenceSet
      if (!otherSet.has(values[i])) {
        differenceSet.add(values[i])
      }
    }
    return differenceSet
  }

First you need to create a new collection differenceSet, representing the set difference of two sets. Next, obtain a first set (Set current class instance) all values, through and determines whether each element is present in the set otherSet, if not present, it indicates that the element is present only in the first set, which was Add to a collection on behalf of the intersection differenceSetin. Finally, return the results.

3.10 isSubset(otherSet)

The current method for determining whether to set a given set of otherSetthe subset .

Mathematical concept of subsets is set Ais a set of Ba subset (or collection Bcomprising a A), expressed as:
\ [A \ subseteq B \]
is defined as follows:
\ [A \ subseteq B = \ {X \ in A \ rightarrow X \ in B \} \]
means is set Ain each of the x(element), but also needs to be present Bin. The following figure shows the set Ais a collection of Bsubsets:

To achieve the following:

// 判断当前集合是否为otherSet的子集
  isSubset(otherSet){
    //如果当前实例中的元素比otherSet实例更多,它就不是一个子集。
    // 子集的元素个数需要小于或等于要比较的集合。
    if (this.size() > otherSet.size()){
      return false
    }
    let values = this.values();
    for (let i = 0; i < values.length; i++) {  // 遍历当前的集合中的元素,判断这个元素是否存在于otherSet中,
     // 如果有一个元素不存在于otherSet中,则表明不是子集
      if (!otherSet.has(values[i])) {
        return false
      }
    }
    return true
  }

First determines whether the current length is greater than the length of a given set of set, if yes, definitely not a subset of a given set, because the number of elements is a subset of the collection must be less than or equal to comparison. Next, all the elements to traverse the collection, validation of these elements are also present in the otherSetmiddle. If there is any element not present in the otherSetmiddle, it means it is not a subset of return false. If all the elements are present in the otherSetmedium, it indicates that the current collection is a subset of a given set of returns true.

4. Summary

This is to achieve the above set of data types, including its method of Example has(value)6: add(value), remove(value), clear(), size(), , values(); methods of operation and three union(otherSet)sets: intersection(otherSet), difference(otherSet), isSubset(otherSet), . Please complete stamp ☞☞☞ the Set

(Finish)

Guess you like

Origin www.cnblogs.com/wangjiachen666/p/11493799.html