Set and WeakSet

Set and WeakSet are native abstractions that allow us to store sequences of unique objects. This is in contrast to arrays, which give you no assurances as to the uniqueness of your values. Here's an illustration:

const foundNumbersArray = [1, 2, 3, 4, 3, 2, 1];
const foundNumbersSet = new Set([1, 2, 3, 4, 3, 2, 1]);

foundNumbersArray; // => [1, 2, 3, 4, 3, 2, 1]
foundNumbersSet; // => Set{ 1, 2, 3, 4 }

As you can see, values given to a Set will always be ignored if they already exist in the Set.

Sets can be initialized by passing an iterable value to the constructor; for example, a string:

new Set('wooooow'); // => Set{ 'w', 'o' }

If you need to convert a Set into an array, you can most simply do this with the spread syntax (as sets are, themselves, iterable):

[...foundNumbersSet]; // => [1, 2, 3, 4]

WeakSets are similar to the previously covered WeakMaps. They are for weakly holding values in a way that allows that value to be garbage-collected in another part of the program. The semantics and best practices around using sets are similar to those concerning arrays. It's advisable to only use sets if you need to store unique sequences of values; otherwise, just use a simple array. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.238.134