Skip to main content

Collections (Set and Map)_ES6 Notes 8

Free2016-05-21#JS#js collection#js set#es6 map#es6 set#js map#es6集合

Completing array deduplication with 1 line of code is somewhat exciting.

I. Purpose and Characteristics of Collections

Collections include Set/WeakSet and Map/WeakMap, similar to hash tables. Characteristics are as follows:

  • Avoids the drawbacks of using objects as hash tables (to avoid prototype properties, you may need to use Object.create(null) to create an empty object with null prototype, rather than the literal {}, because {} === Object.create(Object.prototype))

  • Eliminates conflicts between user data and built-in methods, doesn't expose data as properties, cannot access data through .key or [key], and collections don't inherit key from the prototype chain

  • Collection traversal order is the same as insertion order (and can use new iterator-related features like for...of), while hash table traversal order should theoretically be uncertain (depends on the hash function)

  • Supports has() method for containment detection, faster than indexOf

II. Set

A collection of unique values. Syntax is as follows:

// Create, parameter iterable is optional
new Set(iterable)
// Add, value can be any type
Set.prototype.add(value)
// Delete|Clear
Set.prototype.delete(value)|Set.prototype.clear()
// Check
Set.prototype.has(value)
// Traverse, callback(value, value, set)
Set.prototype.forEach(callbackFn[, thisArg])
// Get element count
Set.prototype.size
// Get various iterators, for Map compatibility, keys === values in Set
set.keys(), set.values() and set.entries()

Characteristics:

  • Automatically deduplicates, duplicate values cannot be added, but 2 objects with identical properties are considered non-duplicate

  • Complete array deduplication with 1 line of code: Array.from(new Set(arr))

  • Avoids conflicts between user data and built-in methods, doesn't expose data as properties, cannot access data through .key or [key], and collections don't inherit key from the prototype chain

Example:

var set = new Set('12231');
// Automatically deduplicate
console.log(set);   // Set {"1", "2", "3"}
// Duplicate values cannot be added
set.add('1');
console.log(set);   // Set {"1", "2", "3"}
set.add(1);
console.log(set);   // Set {"1", "2", "3", 1}
set.add({a: 1});
// Not duplicate
set.add({a: 1});
console.log(set);   // Set {"1", "2", "3", 1, Object {a: 1}, Object {a: 1}}

Two objects with completely identical property values are considered non-duplicate (of course, two references pointing to the same object are duplicate), and the hash function inside Set doesn't support rewriting (for security considerations), so this behavior cannot be changed.

III. Map

A collection of key-value pairs. Syntax is as follows:

// Create, parameter pairs is optional, pairs can be [[key, val], ] 2D array, existing Map, etc.
new Map(pairs)
// Add|Modify/Delete/Clear/Check/Read
map.set(key, val)/map.delete(key)|map.clear()/map.has(key)/map.get(key)
// Traverse, callback(value, key, set), note parameter order
map.forEach(callback)
// Get element count
Map.prototype.size
// Get various iterators, traverse keys/values/key-value pairs
map.keys(), map.values() and map.entries()

Characteristic: key can be any type, including Object (unlike object key which can only be String or Symbol)

Example:

var map = new Map([['a', 1], ['b', 2]]);
//!!! Note parameter order
map.forEach((val, key, arr) => {
    console.log(`val = ${val}, key = ${key}`);
});
// log print:
// val = 1, key = a
// val = 2, key = b
// val = objA, key = [object Object]

Note: map.forEach parameter order is callback(value, key, set), rather than callback(key, value, set) similar to Array.forEach

IV. WeakSet/WeakMap

Weak reference collections with limited functionality. Avoids memory leak problems caused by Set/Map strong references. For example, after set.add(domNode), if domNode is removed, gc cannot reclaim the domNode object because set is a strong reference. Memory can only be reclaimed after calling set.delete(domNode).

Characteristics:

  • WeakSet only supports new, add, delete, has

  • WeakMap only supports new, get, set, delete, has

  • WeakSet values and WeakMap keys must be Object

  • Does not support iteration

  • gc can reclaim invalid elements in Weak collections that are still in use

P.S. The 3rd point is quite strange (possibly for gc considerations)

In short, consider using weak collections in scenarios where memory leaks may occur (such as frequent DOM operations, complex animations, etc.)

V. Summary

Completing array deduplication with 1 line of code is somewhat exciting.

The days of hand-crafting data structures are slowly passing; the underlying infrastructure is being perfected.

References

  • "ES6 in Depth": Free e-book provided by InfoQ Chinese Station

Comments

No comments yet. Be the first to share your thoughts.

Leave a comment