-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathset.js
More file actions
45 lines (31 loc) · 1.24 KB
/
set.js
File metadata and controls
45 lines (31 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// The main feature is that repeated calls of set.add(value) with the same value don’t do anything.
let set = new Set();
let john = { name: "John" };
let pete = { name: "Pete" };
let mary = { name: "Mary" };
// visits, some users come multiple times
set.add(john);
set.add(pete);
set.add(mary);
set.add(john);
set.add(mary);
// set keeps only unique values
console.log(set.size); // 3
for (let user of set) {
console.log(user.name); // John Pete Mary
}
// The alternative to Set could be an array of users, and the code to check for duplicates
// on every insertion using arr.find. But the performance would be much worse,
// because this method walks through the whole array checking every element.
// Set is much better optimized internally for uniqueness checks.
// __ Iteration __
let carsSet = new Set(['BMW', 'Renault', 'Audi']);
let fruits = new Set(['apples', 'oranges', 'kiwis']);
for (const car of carsSet) console.log('for loop:', car);
carsSet.forEach(el => console.log('forEach:', el));
let keys = carsSet.keys();
// => [Set Iterator] { 'BMW', 'Renault', 'Audi' }
let values = carsSet.values();
// => [Set Iterator] { 'BMW', 'Renault', 'Audi' }
let entries = fruits.entries();
// => [Set Iterator] { 'apples', 'oranges', 'kiwis' }