Set
A set is a unique array whose properties you can set only once.
You can’t access the items individually,
and it is not index based.
It is a list of items which we can add to, remove from and loop over
const people = new Set();
people.add(‘AK’);
people.add(‘BK’);
people.add(‘CK’);
>people.size
gives the length of the set
>people.delete(‘BK’);
deletes the item from the set without needing an index
>people.clear();
empties the set
>people.values();
We get a setIterator, which we can .next() over
const it = people.values();
it.next()
it.next()
You can also set a for of loop
for (const person of people){
console.log(person);
}
Declaring a set
1.Normal array like declaration
const students = new Set([‘AK’,’BK’,’CK’]);
2.Convert to set from an existing array
const dogs = [‘Woofer’,’Bowwower’];
const dogSet = new Set(dogs);
.has property
students.has(‘AK’);
-true
Set properties:
add
delete
clear
size
values
Example
Imagine you offer brunch in your restaurant and there is a line for it.
You can handle the line using Set.
const brunch = new Set();
brunch.add(‘AK’);
brunch.add(‘KB’)’
const line = brunch.values();
console.log(line.next().value); //line.next gives us the generator and .value gives us the value
When you call next on a Set, the item removes itself from the Set
You can still add people to the Set after using next
Weak Set
WeakSets can only contain an object type.
You can’t loop over it
There is no .clear() method
WeakSets clean themselves up. When the reference to an item is deleted, it garbage collects automatically
const weakSauce = new WeakSet([dog1, dog2]);
dog1 = null; //dog1 disappears after a few seconds automatically
No comments:
Post a Comment