[Data Structure and Algorithm] JavaScript implements collections and dictionaries

1. Collection structure

1.1. Introduction

The more common implementation method of collection ishash table, which is encapsulated using the JavaScript Object class.

A set is usually composed of a set ofunordered, cannot be repeated element composition.

  • The elements of a set often referred to in mathematics can be repeated, but the elements of a set in computers cannot be repeated.

Sets are special arrays:

  • is special in that the elements have no order, and cannot be repeated< a i=4>.
  • No order meanscannot be accessed by subscript value, cannot be repeated meansthe same There is onlyone copy of the objectin the collection.

Actual set category

  • The Set class in ES6 is a collection class. Here we re-encapsulate a Set class to understand the underlying implementation of the collection.
  • JavaScriptObjectkey is A collection that can be used to encapsulate the collection class Set.

Common operations on collections:

  • add(value): Add a new item to the collection;
  • remove(value):Remove a value from the collection;
  • has(value): If the value is in the set, return true, otherwise return false;
  • clear():Remove all items in the collection;
  • size(): Returns the number of elements contained in the collection, similar to the length attribute of the array;
  • values(): Returns an array containing all values ​​in the collection;

There are other methods, which are not used much and will not be encapsulated here;

1.2. Code implementation
    //封装集合类
    function Set() {
    
    
      //属性
      this.items = {
    
    }

      //方法
      //一.has方法
      Set.prototype.has = value => {
    
    
        return this.items.hasOwnProperty(value)
      }

      //二.add方法
      Set.prototype.add = value => {
    
    
        //判断集合中是否已经包含该元素
        if (this.has(value)) {
    
    
          return false
        }
        //将元素添加到集合中
        this.items[value] = value//表示该属性键和值都为value
        return true//表示添加成功
      }

      //三.remove方法
      Set.prototype.remove = (value) => {
    
    
        //1.判断集合中是否包含该元素
        if (!this.has(value)) {
    
    
          return false
        }

        //2.将元素从属性中删除
        delete this.items[value]
        return true
      }

      //四.clear方法
      Set.prototype.clear = () => {
    
    
        //原来的对象没有引用指向,会被自动回收
        this.items = {
    
    }
      }

      //五.size方法
      Set.prototype.size = () => {
    
    
        return Object.keys(this.items).length
      }

      //获取集合中所有的值
      //六.values方法
      Set.prototype.values = function() {
    
    
        return Object.keys(this.items)
      }
    }

Test code:

    //测试集合类
    //1.创建Set类对象
    let set = new Set()

    //添加元素
    //2.测试add方法
    console.log(set.add('a'));										//67
    console.log(set.add('a'));										//68
    console.log(set.add('b'));										//69
    console.log(set.add('c'));										//70
    console.log(set.add('d'));										//71

    //3.测试values方法
    console.log(set.values());										//74

    //删除元素
    //4.测试remove方法
    console.log(set.remove('a'));									//78
    console.log(set.remove('a'));									//79
    console.log(set.values());										//80

    //5.测试has方法
    console.log(set.has('b'));										//83

    //6.测试size方法和clear方法
    console.log(set.size());										//86
    set.clear()
    // 由于clear方法的实现原理为指向另外一个空对象,所以不影响原来的对象
    console.log(set.size());										//89
    console.log(set.values());										//90

Test Results:

Insert image description here

1.3. Operations between collections

Inter-collection operations:

  • Union: For the given two sets, return a new set containing all elements in the two sets;
  • Intersection: For the given two sets, return a new set containing the common elements in the two sets;
  • Difference set: For the given two sets, return a new set containing all elements that exist in the first set and do not exist in the second set; < /span>
  • Subset: Verify whether a given set is a subset of another set;

Insert image description here

Implementation of union:

Implementation idea: Create set C to represent the union of set A and set B. First add all elements in set A to set C , then traverse the set B, and if it is an element that the set C does not have, add it to the set C.

 Set.prototype.union = otherSet => {
    
    
      // this:集合对象A
      // otherSet:集合对象B
      //1.创建一个新的集合
      let unionSet = new Set()

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

      //3.取出B集合中的元素,判断是否需要加到新集合中
      values = otherSet.values()
      // for(let i of values){
    
    
      //   //由于集合的add方法已经对重复的元素进行了判断,所以这里可以直接添加
      //   unionSet.add(i)
      // }
      for(let i = 0;i < values.length;i++){
    
    
        unionSet.add(values[i])
      }
      return unionSet
    }

Implementation of intersection:

Implementation idea: Traverse set A, and when the obtained element also exists in set B, add the element to another set C.

 Set.prototype.intersection = otherSet => {
    
    
      // this:集合A
      // otherSet:集合B
      //1.创建新的集合
      let intersectionSet = new Set()
      
      //2.从A中取出一个元素,判断是否同时存在于集合B中,是则放入新集合中
      let values = this.values()
      for(let i =0 ; i < values.length; i++){
    
    
        let item = values[i]
        if (otherSet.has(item)) {
    
    
          intersectionSet.add(item)
        }
      }
      return intersectionSet
    }

Implementation of difference set:

Implementation idea: Traverse set A, and when the element obtained does not exist in set B, add the element to another set C.

Set.prototype.diffrence = otherSet => {
    
    
        //this:集合A
        //otherSet:集合B
        //1.创建新的集合
        var diffrenceSet = new Set()

        //2.取出A集合中的每一个元素,判断是否同时存在于B中,不存在则添加到新集合中
        var values = this.values()
        for(var i = 0;i < values.length; i++){
    
    
          var item = values[i]
          if (!otherSet.has(item)) {
    
    
            diffrenceSet.add(item)
          }
        }
        return diffrenceSet
      }

Implementation of subset:

Implementation idea: Traverse set A. When one of the elements obtained does not exist in set B, it means that set A is not a subset of set B and returns false.

 Set.prototype.subset = otherSet => {
    
    
        //this:集合A
        //otherSet:集合B
        //遍历集合A中的所有元素,如果发现,集合A中的元素,在集合B中不存在,那么放回false,如果遍历完整个集合A没有返回false,就返回true
        let values = this.values()
        for(let i = 0; i < values.length; i++){
    
    
          let item = values[i]
          if(!otherSet.has(item)){
    
    
            return false
          }
        }
        return true
      }

2. Dictionary structure

2.1. Introduction

Dictionary features:

  • The dictionary stores key-value pairs, and its main feature is one-to-one correspondence;
  • For example, to save a person's information: array form: [19, 'Tom', 1.65], the information can be retrieved through the subscript value; dictionary form: {"age": 19, "name": "Tom", "height": 165}, the value can be retrieved through key.
  • Besides this, in the dictionarykeyhereimpossible heavy weight andwithout order, butValuepossibleheavy.

The relationship between dictionary and mapping:

  • In some programming languages, this mapping relationship is called dictionary, such as Dictonary in Swift, dict in Python;
  • In some programming languages, this kind of mapping relationship is called Map, such as HashMap&TreeMap in Java;

Common operations on dictionaries:

  • set(key,value): Add new elements to the dictionary.
  • remove(key): Remove the data value corresponding to the key value from the dictionary by using the key value.
  • has(key): If a key value exists in this dictionary, return true, otherwise return false.
  • get(key): Find a specific value through the key value and return it.
  • clear(): Delete all elements in this dictionary.
  • size(): Returns the number of elements contained in the dictionary. Similar to the length property of the array.
  • keys(): Returns all key names contained in the dictionary in the form of an array.
  • values(): Returns all the values ​​contained in the dictionary in the form of an array.
2.2. Encapsulation dictionary

The dictionary class can be implemented based on the object structure in JavaScript, which is relatively simple. Here we directly implement the common methods in the dictionary class.

//封装字典类
function Dictionary(){
    
    
  //字典属性
  this.items = {
    
    }

  //字典操作方法
  //一.在字典中添加键值对
  Dictionary.prototype.set = function(key, value){
    
    
    this.items[key] = value
  }

  //二.判断字典中是否有某个key
  Dictionary.prototype.has = function(key){
    
    
    return this.items.hasOwnProperty(key)
  }

  //三.从字典中移除元素
  Dictionary.prototype.remove = function(key){
    
    
    //1.判断字典中是否有这个key
    if(!this.has(key)) return false

    //2.从字典中删除key
    delete this.items[key]
    return true
  }

  //四.根据key获取value
  Dictionary.prototype.get = function(key){
    
    
    return this.has(key) ? this.items[key] : undefined
  }

  //五.获取所有keys
  Dictionary.prototype.keys = function(){
    
    
    return Object.keys(this.items)
  }

  //六.size方法
  Dictionary.prototype.keys = function(){
    
    
    return this.keys().length
  }

  //七.clear方法
  Dictionary.prototype.clear = function(){
    
    
    this.items = {
    
    }
  }
}

Guess you like

Origin blog.csdn.net/weixin_46862327/article/details/134069244