❝
Interviewer: Tell me about the data structures set and Map in ES6. Apart from this, do you know about WeakSet and WeakMap?
❞
01 preface
When we first started studying ES6, we were sure to wonder what these two data structures were for. Don’t we have enough stacks and queues?
What we can’t understand at the beginning we must respect first. The Set reappears as we get more involved and think of a simpler way to write an array in duplicate. It turns out that this Set is a Set. We learned in high school that sets have unique characteristics, so we understand the meaning of Set. While Map ostensibly means Map, Map has the characteristics of one-to-one correspondence, just like our dictionary, which is the data structure of the dictionary.
02 Set
A Set data structure is similar to an array, but unlike an array, it is unique in that its elements are not repeated, and it is itself a constructor.
const SetArr = new Set(a);
[1.1.2.2.3.3].forEach(item= >SetArr.add(item));
console.log(SetArr);
= >
0: 1
1: 2
2: 3
size: 3
__proto__: Set
Copy the code
As you can see, the printed SetArr is now the only element, and it also has length and a prototype, so just out of curiosity we’ll open the prototype and take a look:
As expected, it has a series of methods, such as the Add method we just used. Let’s explain each property and method in detail:
“Instance attributes“
- The constructor is the Set function
- Size: Returns the length of the set instance
“Instance methods“
- Add (value): To add a value to a Set, return the Set itself
- Delete (value) : deletes a value and returns a Boolean value to determine whether it is successfully deleted
- Has (value): Checks whether there is value and returns a Boolean value
- Clear (): clears all values in Set, no return value
“Traversal methods“
The Set data structure also provides four traversal methods that can be used to traverse its members
- ForEach (): Iterates through elements using the callback function
- Entries (): A traverser that returns key and value pairs and is used to traverse arrays of [key names, key values]
- Values (): Returns a key value traverser used to iterate over all key values
- Keys (): Returns a key name traverser used to iterate over all key names
Let’s see, we can’t seem to find them, but I’ll give you a little example, and you’ll see. Because the Set structure is a key-value only structure, all keys methods return the same as values methods.
forEach
let s = new Set([1.2.3.4.5]);
s.forEach(item= >{console.log(item+1)})
//2 3 4 5 6
Copy the code
entries
let s =new Set(['a'.'b'.'c'])
for(let item of s.entries()){
console.log(item)
}
(2) ["a"."a"]
(2) ["b"."b"]
(2) ["c"."c"]
Copy the code
values
let s =new Set(['a'.'b'.'c'])
for(let item of s.values()){
console.log(item)
}
a
b
c
Copy the code
keys
let s =new Set(['a'.'b'.'c'])
for(let item of s.keys()){
console.log(item)
}
a
b
c
Copy the code
“Use the Set structure to implement cross and union difference“
let a = new Set([1.2.3]);
let b = new Sect([3.4.5]);
/ / intersection
let value = new Set([...a].filter(item= >b.has(item)));
/ / and
let value = new Set([...a],[...b])
/ / poor
let value = new Set([...a].filter(item= >! b.has(item)));
Copy the code
03 WeakSet
From the literal meaning, it is a WeakSet structure, the specific weakness is reflected in the WeakSet members can only be objects, and another is that WeakSet objects are weak references, that is, garbage collection mechanism does not consider the WeakSet reference to the object. That is, none of the references in WeakSet count toward garbage collection.
In addition to the different definitions, WeakSet has no size attribute and cannot perform traversal operation, because it will disappear at any time and members are not suitable for reference. If the garbage collection mechanism is running, the number of members may be different.
The “method” cannot iterate, so there are no traversal methods, only instance methods.
- Add (): Add new members to WeakSet
- Delete (): Deletes a WeakSet member
- Has (): Judge whether A WeakSet contains an element
04 Map
The Set structure that we talked about above has no keys and only values, while the Map structure is a combination of keys and values, which resolves the previous restriction that we can only use strings as keys. This means that we can use various data types (or objects) as keys.
let map = new Map(a);
let obj = {name:'alan'.age:20};
map.set(obj,'Here are some descriptions.');
map.get(obj);
console.log(map);
Copy the code
We can also print out what is in the map, in addition to the same methods as Set, we can see more get and Set methods.
“attribute“
- Constructor: Map constructor
- Size: Map element length
“Instance methods“
- Set (key, value): Sets the value of the key
- Get (key): obtains the value of the key. Otherwise, undefined
- Has (key) : Indicates whether a key is contained
- Delete (key): deletes a key. If the deletion fails, false is returned
- Clear (): Clears all members
“Traversal methods“
- ForEach (): Iterates through members using the callback function
- Entries (): Returns all member traversers
- Keys (): Returns the key name traverser
- Values (): Returns a key value traverser
entries
let person = new Map([['name'.'alan'], ['age'.'20']]);
for(let item of person.entries()){
console.log(item)
}
Copy the code
keys
let person = new Map([['name'.'alan'], ['age'.'20']]);
for(let item of person.keys()){
console.log(item)
}
//name
//age
Copy the code
values
let person = new Map([['name'.'alan'], ['age'.'20']]);
for(let item of person.keys()){
console.log(item)
}
//alan
/ / 20
Copy the code
Conversion with other data structures
- Turn the Map array
let person = new Map([['name'.'alan'], ['age'.'20']]);
console.log(... person)
//[['name','alan'],['age','20']]
Copy the code
- Array to the Map
let arr = [['name'.'alan'], ['age'.'20']].
let m = new Map(arr);
//Map(2) {"name" => "alan", "age" => "20"}
Copy the code
- Turn the Map object
let person = new Map([['name'.'alan'], ['age'.'20']]);
function swap(map){
let obj = Object.create(null);
for(let [key,value] of map){
obj[key]=value;
}
return obj
}
swap(person);
//{name: "alan", age: "20"}
Copy the code
- Object to turn the Map
let person ={'name':'alan'.'age':'20'};
function swap(obj){
let map = new Map(a);
for(let key of Object.keys(obj)){
map.set(key,obj[key]);
}
return map
}
swap(person);
Copy the code
05 WeakMap
WeakMap can generate a set of key-value pairs just like Map, but there are also differences, mainly including the following two points:
- WeakMap only accepts objects as key names (excluding NULL)
- The object to which the key name refers is not counted in the garbage collection mechanism
Similar to WeakSet, WeakMap also has no traversal operation, no size attribute, no way to list all key names (due to the operation of garbage collection mechanism), nor can it be emptied.
“Instance methods“
- get()
- set()
- has()
- delete()
06 summary
From this summary, you should have a general idea of these data structures and the differences between them. When we studied before, we often ignored the understanding of WeakSet and WeakMap, and did not know their relationship with garbage collection mechanism. It is your weak-reference relationship that allows the structure of the two data to be used to avoid memory leaks.