Create an immutable set in JavaScript
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// Create a proxy handler that prevents mutation const handler = { get(target, prop) { // If the property is a mutating function, return an empty function if (["add", "delete", "clear"].includes(prop)) { return() => {}; } // Otherwise, return the original property value return target[prop]; }, }; // Create a set const mySet = new Set([1, 2, 3]); // Create a proxy object that wraps the set const immutableSet = new Proxy(mySet, handler); // Try to modify the set // Does nothing immutableSet.add(4); // Does nothing immutableSet.delete(3); // Does nothing immutableSet.clear(); // Log the set console.log(immutableSet); // Set(3) { 1, 2, 3 } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Create a set const mySet = new Set([1, 2, 3]); // Convert the set to an array and freeze it const frozenArray = Object.freeze([...mySet]); // Try to modify the array - throws an error try { // TypeError: Cannot add property 3, object is not extensible frozenArray.push(4); } catch (e) { console.log(e.name + ': ' + e.message); } try { // TypeError: Cannot delete property '2' of [object Array] frozenArray.pop(); } catch (e) { console.log(e.name + ': ' + e.message); } // Log the array console.log(frozenArray); // [ 1, 2, 3 ] |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Import Immutable.js const Immutable = require("immutable"); // Create a set using Immutable.Set const mySet = Immutable.Set([1, 2, 3]); // Try to modify the set using Immutable functions // Returns a new set with 4 added const newSet = mySet.add(4); // Returns a new set with 3 deleted const anotherSet = mySet.delete(3); // Log the sets console.log(mySet); // Set { 1, 2, 3 } console.log(newSet); // Set { 1, 2, 3, 4 } console.log(anotherSet); // Set { 1, 2 } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// reference to an array to be inserted into a set and modified later var arr = [2, 3]; // Create a set const mySet = new Set([1, arr]); // Convert the set to an array and freeze it const frozenArray = Object.freeze([...mySet]); // Log the array console.log(frozenArray); // [1, [2, 3]] // modify the array instance inside the set arr[0] = 4; // Log the array console.log(frozenArray); // [1, [4, 3]] |
That’s all about creating an immutable set in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)