chapter ten

10 Dealing with collections

 

This chapter covers

  • Using array functions
  • Creating dictionaries with maps
  • Managing unique values with sets
  • How to preserve immutable collections

Now that we’ve spent some time wrangling the particularities of objects in JavaScript, we’ll move on to a closely related topic: collections. We’ll start with arrays, the most common type of collection in JavaScript. We’ll explore some of the built-in array methods that allow you to take advantage of functional programming paradigms.

Next we’ll meet two newer collection types: maps and sets. Maps are collections of key-value pairs with capabilities beyond those of ordinary objects. Sets are collections of items in which no item can appear more than once.

Lastly, we’ll discuss mutability and why it’s often desirable for objects and collections to be immutable. We’ll see how TypeScript can guard against mutations with read-only types. We’ll also meet a popular package, Immer, that provides a convenient way to work with immutable objects and collections.

Let’s begin our exploration with the simplest and most common of all collections: arrays.

10.1 Arrays

If your programming background is in a typed language such as C, you might think of arrays as sequential chunks of memory that house items of the same type, where each chunk of memory is of fixed size and has an associated index through which you can easily access it.

10.1.1 Creating arrays

10.1.2 Adding and removing items at either end of an array

10.1.3 Adding and removing items at any array location

10.1.4 Common operations on arrays

10.2 Maps

10.2.1 Creating our first map

10.2.2 Iterating over maps

10.2.3 Weakly holding references with WeakMap

10.3 Sets

10.3.1 Creating our first set

10.3.2 Combining and comparing sets

10.3.3 Weakly holding references with WeakSet

10.4 Mutable and immutable collections

10.4.1 The perils of mutability

10.4.2 Read-only collections in TypeScript

10.4.3 Immutable transformations with Immer

10.5 Summary