This post will discuss how to create an immutable set in JavaScript.

There is no built-in way to create an immutable set in JavaScript, as sets are mutable by default, which means we can add, delete, or modify the elements of a set after it is created. However, there may be situations where we want to create an immutable set, which means we cannot change the elements of the set once it is created. However, there are some possible workarounds to achieve immutability for sets:

1. Using a proxy

We can create a proxy object that wraps around a set and intercepts any attempts to modify it, such as calling the add, delete, or clear functions. We can either throw an error or simply ignore these operations. For instance:

Download  Run Code

2. Using Object.freeze() function

We can use the Object.freeze() function to make an object immutable, meaning that its properties cannot be added, removed, or changed. However, this does not work directly on sets, as they are not plain objects. We can convert the set to an array and then freeze it. For instance:

Download  Run Code

3. Using a library

We can use a third-party library that provides immutable data structures, such as Immutable.js or Immer. These libraries offer various functions and features to create and manipulate immutable sets and other collections. For example, we can use Immutable.js library to create an immutable set by using the Set() constructor function. This function creates a truly immutable set that cannot be changed in any way. Immutable.js provides the add() or delete() functions to manipulate the set, but they return a new set instance instead, leaving the original set untouched.

Download Code

 
Note that all the above functions only freezes the set itself, not the elements inside it. If the elements are objects or arrays, they can still be modified. The following code illustrates this:

Download  Run Code

That’s all about creating an immutable set in JavaScript.