Let JS Map show its original shape with a small hand

I. Preface

This article mainly talks about the usage of JS Map object and how to write Map, which is very suitable for the students who have preliminarily learned JS. It is very helpful for JS understanding and interview to properly learn the skills of writing JS source code. Most people know the use of Map method, but there are few articles about Map source code implementation on the Internet. I hope this article can help you understand Map method.

Said ahead

The Map object holds key value pairs and remembers the original insertion order of the keys. Any value (object or original) can be a key or a value. This article will introduce the usage first, then the handwritten Map,
If you want Map to be original, please take a few minutes to browse this article!

2, Use of Map method

Map is the structure of a set of key value pairs, with extremely fast search speed.

For example, suppose that you want to find the corresponding grades according to the names of classmates. If you use Array to realize this, you need two arrays:

var names = ['lm', 'dz', 'xxy'];
var scores = [100, 90, 80];

We need to achieve this requirement. First, we need to traverse the names array, find the location where we need to query the names of classmates, and then go to the scores array to find the corresponding location and get the scores. There are two disadvantages in this way:

  1. The longer the array, the longer it takes to query.
  2. If there is a lot of data, it is easy to make mistakes when importing data.

If you use Map, you only need a "name" - "score" cross reference table. You can find the score directly according to the name. A key (name) and a corresponding value (score) are bound. No matter how big the table is, you don't have to worry about making mistakes. The implementation of Map with JavaScript is as follows:

var m = new Map([['lm', 100], ['dz', 90], ['xxy', 80]]);
m.get('lm'); //100
m.size();//3
m.set('xp', 90); // Add new key value
m.delete('xxy'); // Delete key 'xxxy'

Through the get method of Map, 100 points of lm students are found, how many key value pairs are obtained by size, xp scores are added by set method, and xxy scores are deleted by delete method.

We need to note that a key can only correspond to one value. Put value into a key multiple times, and the later value will flush out the previous value:

var m = new Map();
m.set('xp', 70);
m.set('xp', 90);
m.get('xp'); // 90

3, Handwritten Map method

To write a Map method, the first thing you need to know is the new data type of its ES6 standard, which is a collection of key / value pairs. This data type can be operated in many ways. Now let's, with a little hand, show it~

  • Define Map method

    The first thing to write a method is to define it and declare the parameters in the method.

/** 
    *  
    * Description: map method of js implementation 
    * @returns {Map} 
    */  
   function Map(){  
       var struct = function(key, value) {  
        this.key = key;  
        this.value = value;  
       }; 
   }
  • Writing set method

    We need to add a key value pair. We need to note that if the key value pair already exists, its value needs to be overwritten and updated. If it does not exist, the pair of key values are saved directly.

// Add map key value pair  
        var set = function(key, value){
        //Traversal array, overwrite if present
          for (var i = 0; i < this.arr.length; i++) {  
          if ( this.arr[i].key === key ) {  
           this.arr[i].value = value;  
           return;  
          }  
         };
         //There is no key pair value in the previous data, so it is saved directly
         this.arr[this.arr.length] = new struct(key, value);  
        };  
  • Writing get method

    To complete the get method, you need to obtain the value according to the key. If the key exists, you need to obtain the corresponding value. Otherwise, null is returned. The code is as follows:

//  Get value according to key   
        var get = function(key) {  
         for (var i = 0; i < this.arr.length; i++) {  
          if ( this.arr[i].key === key ) {  
           return this.arr[i].value;  
          }  
         }  
        return null;  
        };  
  • Write remove method

In the Map method, the key can be used to delete key value pairs. To delete the key value pair, the author thinks that, no matter whether it exists or not, traverse all arrays, first take out the v.key at the top of the stack with pop, if the key to be deleted is consistent with v.key, continue, otherwise unshift(v) will be used to recover it. The code is as follows:

//   Delete according to key  
        var remove = function(key) {  
         var v;  
         for (var i = 0; i < this.arr.length; i++) {  
          v = this.arr.pop();  
          if ( v.key === key ) {  
           continue;  
          }  
          this.arr.unshift(v);  
         }  
        };  
  • Write size and isEmpty methods

The implementation of these two methods is very simple. I believe everyone will, and I will directly go to the code:

//   Get the number of map key value pairs  
        var size = function() {  
         return this.arr.length;  
        };  
       // Determine whether the map is empty    
        var isEmpty = function() {  
         return this.arr.length <= 0;  
        };  

4, Verification and summary

  • Verification

The best way to verify whether a method has been written correctly is to practice to get real knowledge. I'll attach all the codes below

    function Map(){  
        var struct = function(key, value) {  
         this.key = key;  
         this.value = value;  
        };  
       // Add map key value pair  
        var set = function(key, value){  
          for (var i = 0; i < this.arr.length; i++) {  
          if ( this.arr[i].key === key ) {  
           this.arr[i].value = value;  
           return;  
          }  
         };  
         this.arr[this.arr.length] = new struct(key, value);  
        };  
       //  Get value according to key   
        var get = function(key) {  
         for (var i = 0; i < this.arr.length; i++) {  
          if ( this.arr[i].key === key ) {  
           return this.arr[i].value;  
          }  
         }  
        return null;  
        };  
       //   Delete according to key  
        var remove = function(key) {  
         var v;  
         for (var i = 0; i < this.arr.length; i++) {  
          v = this.arr.pop();  
          if ( v.key === key ) {  
           continue;  
          }  
          this.arr.unshift(v);  
         }  
        };  
       //   Get the number of map key value pairs  
        var size = function() {  
         return this.arr.length;  
        };  
       // Determine whether the map is empty    
        var isEmpty = function() {  
         return this.arr.length <= 0;  
        };  
        this.arr = new Array();  
        this.get = get;  
        this.set = set;  
        this.remove = remove;  
        this.size = size;  
        this.isEmpty = isEmpty;  
       }

       var map=new Map();  
       map.set("xxyang",100);
       map.set("xxyang",90);
       map.set("xp","dz");
       console.log(map.get('xxyang'));//90
       console.log(map.get('xp')); //dz
       console.log(map.size());//2  
       map.remove("xxyang");
       console.log(map.size());//1  
       console.log(map.get("xxyang"));//null       
 

The following results are obtained by running vscode:


The results are correct and can be covered. The simple implementation of Map method is finished. After reading the article, you can try other methods~

  • summary
  1. The key of Map can be any value, including function, object and basic type.
  2. The key values in a Map are ordered, so when traversing it, the Map object returns the key values in the order in which they were inserted.
  3. Map can be iterated directly
  4. Map has some performance advantages in scenarios involving frequent addition and deletion of key value pairs.
  5. For Xiaobai, it's a good choice to choose a simple method to implement the source code. It can break your inner fear. If you have this fear, try it. Handwritten source code, interview often test, although there are many bigwigs, also published relevant articles, but the backrest is not remember, or to write their own.

End

Congratulations on reading this article. If there are any mistakes, please point them out to me! If you think it's good, come on A kind of Cheer up, ha ha

Reference articles

Published 3 original articles, won praise 5, visited 987
Private letter follow

Tags: Javascript

Posted on Thu, 05 Mar 2020 22:40:08 -0800 by crazycoders