阿里云主机折上折
  • 微信号
Current Site:Index > The new set operation

The new set operation

Author:Chuan Chen 阅读数:56196人阅读 分类: JavaScript

New Methods for Collection Types

ECMAScript 15 introduces several utility methods for the Set and Map collection types, significantly enhancing the convenience of collection operations. These new methods include Set.prototype.union(), Set.prototype.intersection(), Set.prototype.difference(), and others, providing native support for set operations.

const setA = new Set([1, 2, 3]);
const setB = new Set([3, 4, 5]);

// Union
const union = setA.union(setB); // Set {1, 2, 3, 4, 5}

// Intersection
const intersection = setA.intersection(setB); // Set {3}

// Difference
const difference = setA.difference(setB); // Set {1, 2}

Interoperability Between Collections and Arrays

The new Set.from() and Set.prototype.toArray() methods simplify the conversion process between collections and arrays. Set.from() supports creating a set from an iterable object, while toArray() converts a set into an array while preserving element order.

// Create a set from an array
const arr = [1, 2, 2, 3];
const set = Set.from(arr); // Set {1, 2, 3}

// Convert set to array
const newArr = set.toArray(); // [1, 2, 3]

// Preserves insertion order
const orderedSet = new Set();
orderedSet.add('z');
orderedSet.add('a');
orderedSet.toArray(); // ['z', 'a']

Enhanced Operations for Map Collections

The Map type introduces a new static method groupBy(), which groups elements based on the return value of a callback function. This method returns a Map instance where the keys are the grouping criteria and the values are arrays of corresponding elements.

const inventory = [
  { name: 'asparagus', type: 'vegetables' },
  { name: 'bananas',  type: 'fruit' },
  { name: 'goat', type: 'meat' },
  { name: 'cherries', type: 'fruit' }
];

const grouped = Map.groupBy(inventory, ({ type }) => type);

/*
Map {
  'vegetables' => [{ name: 'asparagus', type: 'vegetables' }],
  'fruit' => [
    { name: 'bananas', type: 'fruit' },
    { name: 'cherries', type: 'fruit' }
  ],
  'meat' => [{ name: 'goat', type: 'meat' }]
}
*/

Batch Operations for Collections

The new addAll() and deleteAll() methods support batch operations on collections. addAll() allows adding multiple elements at once, while deleteAll() enables batch deletion of elements. Both methods return a reference to the modified collection.

const colors = new Set(['red', 'green']);

// Batch add
colors.addAll('blue', 'yellow');
// Set {'red', 'green', 'blue', 'yellow'}

// Batch delete
colors.deleteAll('green', 'red');
// Set {'blue', 'yellow'}

Extended Mathematical Operations for Collections

In addition to basic union, intersection, and difference operations, ECMAScript 15 introduces the symmetricDifference() method to compute the symmetric difference, which consists of elements present in exactly one of the two sets.

const setX = new Set([1, 2, 3]);
const setY = new Set([2, 3, 4]);

const symDiff = setX.symmetricDifference(setY);
// Set {1, 4}

Predicate Methods for Collections

The new every() and some() methods are introduced for assertion testing on collection elements. every() requires all elements to satisfy the condition, while some() only needs at least one element to meet the condition, behaving consistently with their array counterparts.

const numbers = new Set([1, 2, 3, 4, 5]);

// All elements are less than 10
numbers.every(x => x < 10); // true

// At least one even element exists
numbers.some(x => x % 2 === 0); // true

Functional Extensions for WeakSet

WeakSet now includes addAll() and deleteAll() methods, enabling batch operations on weakly referenced collections. These methods maintain weak reference characteristics while improving operational efficiency.

const obj1 = {}, obj2 = {}, obj3 = {};
const weakSet = new WeakSet();

// Batch add weak references
weakSet.addAll(obj1, obj2);
weakSet.has(obj2); // true

// Batch delete
weakSet.deleteAll(obj1, obj2);
weakSet.has(obj1); // false

Enhanced Iteration for Collections

The values(), keys(), and entries() methods now return iterable collection views that can be directly used in for...of loops. The new forEach() method allows binding a this value as its second parameter.

const techSet = new Set(['js', 'css', 'html']);

// Directly iterate over values
for (const tech of techSet.values()) {
  console.log(tech); // 'js', 'css', 'html'
}

// Binding context
const printer = {
  log: function(item) {
    console.log(this.prefix + item);
  },
  prefix: 'Tech: '
};

techSet.forEach(printer.log, printer);
// Output: 'Tech: js', 'Tech: css', 'Tech: html'

Capacity Management for Collections

The new resize() method allows dynamic adjustment of a collection's storage capacity. Preallocating space can optimize performance when expecting significant changes in the number of elements.

const largeSet = new Set();

// Preallocate space
largeSet.resize(1000);

// Add a large number of elements
for (let i = 0; i < 800; i++) {
  largeSet.add(i);
}

JSON Conversion for Collections

The new toJSON() method and Set.fromJSON() static method enable bidirectional conversion between collections and JSON format. toJSON() returns an array containing the collection's elements, while fromJSON() reconstructs a set from an array.

const originalSet = new Set([1, 2, 3]);

// Convert set to JSON
const jsonStr = JSON.stringify(originalSet);
// '[1,2,3]'

// Convert JSON to set
const parsedSet = Set.fromJSON(jsonStr);
// Set {1, 2, 3}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.