Set collection type

Keywords: Javascript

ECMAScript 6 adds a Set set type to bring a Set data structure to the language. Sets are like enhanced maps in many ways because most of their API s and behaviors are common.

6.6.1 basic API

  1. You can create an empty collection using the new keyword and the Set constructor. If you want to initialize the instance while creating, you can pass an iteratable object to the Set constructor, which needs to contain the elements inserted into the collection instance.

    const m = new Set();
    // Initializing a collection with an array
    const sl = new Set(
      [
        "val1","val2","val3"
      ]
    )
    console.log(sl.size); // 3
    
    // Initializing a collection using a custom iterator
    const s2 = new Set({
      [Symbol.iterator]: function* () {
        yield "val1";
        yield "val2";
        yield "val3"
      }
    })
    console.log(s2); // Set { 'val1', 'val2', 'val3' }
    
  2. After initialization, you can use add() to increase the value, has() to query, size to get the number of elements, and delete() and clear() to delete elements.

  3. add() returns an instance of a collection, so you can connect multiple add operations, including initialization.

    const s = new Set();
    console.log(s.has("Matt")); // false
    console.log(s.size); // 0
    
    s.add("Matt").add("frisbie");
    console.log(s.has("Matt")); // true
    console.log(s.size); // 2
    
    s.delete("Matt"); 
    console.log(s.has("Matt")); // false
    console.log(s.has("frisbie")); // true
    console.log(s.size); // 1
    
    s.clear();
    
    console.log(s.has("Matt")); // false
    console.log(s.has("frisbie")); // false
    console.log(s); // set {}
    
    const ss = new Set().add("vall");
    ss.add("val2").add("val3");
    console.log(ss); // Set { 'vall', 'val2', 'val3' }
    
  4. Similar to Map, set can contain any JavaScript data type as a value, and the set also uses the SameValueZero operation, which is basically equivalent to using strict object equality criteria to check the matching of values. Like strict equality, objects and other collection types used as values do not change when their contents or properties are modified.

  5. The add() and delete() operations are idempotent, and delete() returns a Boolean value indicating whether there is a value to delete in the collection.

    const s = new Set();
    const functionVal = function () { };
    const symbolVal = Symbol();
    const objectVal = new Object();
    
    s.add(functionVal).add(symbolVal).add(objectVal);
    console.log(s.has(functionVal)); // true
    console.log(s.has(objectVal)); // true
    console.log(s);   // Set { [Function: functionVal], Symbol(), {} }
    
    // Checking means that independent instances do not conflict
    console.log(s.has(function () { })); // false
    
    const a = new Set();
    const objVal = {};
    const arrVal = [];
    a.add(objVal);
    a.add(arrVal);
    
    objVal.bar = "bar";
    arrVal.push("bar");
    
    console.log(a.has(objVal)); // true
    console.log(a.has(arrVal)); // true
    console.log(a); // Set { { bar: 'bar' }, [ 'bar' ] }
    
    const x = new Set();
    x.add('foo');
    console.log(x.size); // 1
    x.add('foo');
    console.log(x.size); // 1
    
    console.log(x.delete('foo')); // true
    console.log(x.delete('foo')); // false
    

6.6.2 sequence and iteration

  1. Set maintains the order in which values are inserted, so it supports sequential iteration. Collection instances can provide an iterator that can generate collection contents in insertion order. The iterator may be obtained through the values() method and its alias method keys(), or the Symbol.iterator attribute, which references values().

  2. Because values() is the default iterator, you can directly use the extension operation on the collection instance to convert the collection into an array. The entries () method of the collection returns an iterator, which can generate an array containing two elements in the insertion order. These two elements are the repetition of each value in the collection.

    const s = new Set(["val1","val2","val3"]);
    console.log(s.values === s[Symbol.iterator]); // true
    console.log(s.keys === s[Symbol.iterator]); // true
    
    for (let value of s.values()) {
      console.log(value);
    }
    // val1
    // val2
    // val3
    for (let value of s[Symbol.iterator]()) {
      console.log(value);
    }
    // val1
    // val2
    // val3
    console.log([...s]); // [ 'val1', 'val2', 'val3' ]
    
    for (let pair of s.entries()) {
      console.log(pair);
    }
    // ['val1', 'val1']
    // ['val2', 'val2']
    // ['val3', 'val3']
    
  3. If you do not use an iterator but a callback, you can call the forEach() method of the collection and pass in a callback to iterate over each key value pair in turn. The incoming callback receives an optional second parameter, which is used to override the value of this inside the callback.

    const s = new Set(["val1", "val2", "val3"]);
    s.forEach((val, dupVal) => console.log(`${val}->${dupVal}`))
    // val1 - > val1
    // val2 - > val2
    // val3 - > val3
    
    const s1 = new Set(["val1"]);
    // The original value of the string is not modified as a value
    for (let value of s1.values()) {
      value = "newval";
      console.log(value); // newval
      console.log(s1.has("val1")); // true
    }
    const valObj = {id:1} 
    const s2 = new Set([valObj]);
    
    // Modify the properties of the value object, but the object still exists in the collection
    for (let value of s2.values()) {
      value.id = "newVal";
      console.log(value); // { id: 'newVal' }
      console.log(s2.has(valObj)); // true
    }
    console.log(valObj); // { id: 'newVal' }
    

6.6.3 define formal collection operations

I don't quite understand it at present, so I don't need any description text and code first.

Posted by Garrett on Wed, 01 Sep 2021 13:06:42 -0700