-
Notifications
You must be signed in to change notification settings - Fork 1
/
sets.js
60 lines (45 loc) · 1.66 KB
/
sets.js
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/** Sets **/
// Sets are iterable.
// Set constructor accepts an iterable.
// e.g. [keyOne, keyTwo]
var set = new Set(['foo', 'bar'])
console.log(set) // Set { 'foo', 'bar' }
// Keys must be unique.
set.add('foo')
set.add('foo')
// If the value already exists.
// It will not be added again.
console.log(set) // Set { 'foo', 'bar' }
// Property .size
console.log(set.size) // 2
// .keys()
// Returns a new Iterator object containing the keys
// for each element in the Set, in insertion order.
var keysIterator = set.keys() // SetIterator { 'foo', 'bar' }
console.log(keysIterator.next().value) // 'foo'
console.log(keysIterator.next().value) // 'bar'
// .values()
// The same as the .keys() function and returns an Iterator object
// containing the values for each element in the Set, in insertion order.
var valuesIterator = set.values()
console.log(valuesIterator.next().value) // 'foo'
console.log(valuesIterator.next().value) // 'bar'
// .entries()
// Returns a new Iterator object containing an array of [value, value]
// for each element in the Set, in insertion order.
// This structure is to keep Sets like Map objects, [key, value], however
// because Sets have no keys this returns an array of [value, value].
var entriesIterator = set.entries()
console.log(entriesIterator.next().value) // ['foo', 'foo']
console.log(entriesIterator.next().value) // ['bar', 'bar']
// .add()
// Adds a new element into the Set object.
set.add('zed')
console.log(set) // Set { 'foo', 'bar', 'zed' }
// .has()
// Checks if an element exists on the Set.
console.log(set.has('zed')) // true
// .delete()
// Remove an element from the Set.
set.delete('zed')
console.log(set) // Set { 'foo', 'bar' }