concept set in category javascript

appears as: set, sets, A set, Set, The set
Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond

This is an excerpt from Manning's book Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond.

Here’s some code that maps a set of numbers, applying an exponent to each of them. Notice how you’re using that=this to maintain context inside the anonymous function passed to map. The map function in particular accepts a second parameter that sets the context, but many functions don’t provide such a convenience, leaving developers to come up with work-arounds like the that=this used here. How many times have you had to write code like this? Wouldn’t it be nice if there were an elegant way to maintain the outer context?

Sets are a new type of object in JavaScript. A set is a unique collection of data. It can store any data type but won’t store duplicate references to the same value. Sets are iterables, so you can use spread and for..of with them. Sets are most closely related to arrays; however, when you use an array your focus is generally on the individual items in the array. When dealing with a set, you’re usually dealing with the set as a whole.

The property Set.prototype.size is equivalent to the length property of a string or an array. Additionally the method add that you’ve been using is very similar to the push method of an array, which adds an item to the end of the array’s list of items. But the delete function has no array counterpart. You can easily remove an item from an array using pop or shift. (pop removes and returns the last item from the array; shift removes and returns the first item, which also causes all the other items indices to shift down by one.) But these functions delete values based on their position, last and first, respectively. The delete method of a set specifies to delete a specific value from the set, no matter its position. This concept wouldn’t carry over to arrays easily because an array could have the specific value in more than one location. You could convert an array to set and then use delete to remove the item, but it would have the side effect of also uniquing the array, which may not be desired. On the flip side, sets have no equivalent methods for pop or shift. But sets do maintain insertion order, so you could easily convert a set to an array to get the first or last item:

function pop(set) {
  return [ ...set ].pop();
}

When you use spread with a Set like [ ...set ], we’re creating a new Array with all the individual values from the set used as items in the array. This function would return the last item in a set, but it wouldn’t remove it because using spread on an iterable does not alter the iterable. The newly created array would have its last item removed, but not the set. To also remove the last item from the set, you would have to make sure you delete it from the set as well:

In this lesson, you learned how to create and use sets and why you would use one over an array.

  • A set has a new literal and must be created using new.
  • You can create a set using an iterable as an argument.
  • You can clone a set by creating a new set with an existing set as an argument.
  • Sets are iterables and thus can be used with spread and for..of.
  • You add a value to a set using Set.prototype.add.
  • You can tell if a set has a value using Set.prototype.has.
  • You can remove a value from a set using Set.prototype.delete.
  • You can empty a set by using Set.prototype.clear.
  • You can determine how many items a set contains with Set.prototype.size.
  • Secrets of the JavaScript Ninja, Second Edition

    This is an excerpt from Manning's book Secrets of the JavaScript Ninja, Second Edition.

  • Maps, which we can use to create dictionary collections; and sets, which allow us to deal with collections of unique items
  • Next, we’ll discuss two new ES6 collections: maps and sets. Using maps, you can create dictionaries of a sort that carry mappings between keys and values—a collection that’s extremely useful in certain programming tasks. Sets, on the other hand, are collections of unique items in which each item can’t occur more than once. Let’s begin our exploration with the simplest and most common of all collections: arrays.

    The mapping of course exists for the first two ninjas, but it doesn’t exist for the third ninja, because we haven’t used the third ninja as an argument to the set method. The current state of the map is shown in figure 9.14.

    Figure 9.14. A map is a collection of key-value pairs, where a key can be anything—even another object.

    In addition to get and set methods, every map also has a built-in size property and has and delete methods. The size property tells us how many mappings we’ve created. In this case, we’ve created only two mappings.

    9.3.3. Intersection of sets

    The intersection of two sets, A and B, creates a set that contains elements of A that are also in B. For example, we can find ninjas that are also samurai, as shown next.

    Listing 9.22. Intersection of sets
    const ninjas = new Set(["Kuma", "Hattori", "Yagyu"]); const samurai = new Set(["Hattori", "Oda", "Tomoe"]); const ninjaSamurais = new Set( [...ninjas].filter(ninja => samurai.has(ninja)) #A ); assert(ninjaSamurais.size === 1, "There's only one ninja samurai"); assert(ninjaSamurais.has("Hattori"), "Hattori is his name"); #A - Uses the spread operator to turn our set into an array so we can use the array’s filter method to keep only ninjas that are contained in the samurai set !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":10,\"ch\":0},{\"line\":10,\"ch\":157}]]"} !@%STYLE%@!

    The idea behind listing 9.22 is to create a new set that contains only ninjas who are also samurai. We do this by taking advantage of the array’s filter method, which, as you’ll remember, creates a new array that contains only the items that match a certain criterion. In this case, the criterion is that the ninja is also a samurai (is contained in the set of samurai). Because the filter method can only be used on arrays, we have to turn the ninjas set into an array by using the spread operator:

    CORS in Action: Creating and consuming cross-origin APIs

    This is an excerpt from Manning's book CORS in Action: Creating and consuming cross-origin APIs.

    The XMLHttpRequest object handles the server’s response through a set of events. Events are functions that are invoked at specific moments in the lifecycle of an HTTP request. Events aren’t unique to the XMLHttpRequest object; when a user clicks a link on an HTML page, the browser fires a click event.

    Figure 4.19. An HTTP request as a set of Russian dolls. Requests may fail for various reasons, and a successful preflight doesn’t imply a successful request.

    This example contains a lot of steps, but a determined hacker will use any tools at his disposal to get at the information he wants. If a document or API needs to be accessible to a group of users, it’s best to limit the set of origins. The next section looks at how to do this.