Immutability refers to the inability to change the value of a variable after a value has been assigned to it. Purely functional programming languages include immutable implementations of common data structures. For example, when we add an element to an array, we are mutating the original array. However, if we use an immutable array and we try to add a new element to it, the original array will not be mutated, and we will add the new item to a copy of it.
The following code snippet declares a class named ImmutableList that demonstrates how it is possible to implement an immutable array:
class ImmutableList<T> {
private readonly _list: ReadonlyArray<T>;
private _deepCloneItem(item: T) {
return JSON.parse(JSON.stringify(item)) as T;
}
public constructor(initialValue?: Array<T>) {
this._list = initialValue || [];
}
public add(newItem: T) {
const clone = this._list.map(i => this._deepCloneItem(i));
const newList = [...clone, newItem];
const newInstance = new ImmutableList<T>(newList);
return newInstance;
}
public remove(
item: T,
areEqual: (a: T, b: T) => boolean = (a, b) => a === b
) {
const newList = this._list.filter(i => !areEqual(item, i))
.map(i => this._deepCloneItem(i));
const newInstance = new ImmutableList<T>(newList);
return newInstance;
}
public get(index: number): T | undefined {
const item = this._list[index];
return item ? this._deepCloneItem(item) : undefined;
}
public find(filter: (item: T) => boolean) {
const item = this._list.find(filter);
return item ? this._deepCloneItem(item) : undefined;
}
}
Every time we add an item to, or remove it from, the immutable array, we create a new instance of the immutable array. This implementation is very inefficient, but it demonstrates the basic idea. We are going to create a quick test to demonstrate how the preceding class works. We are going to use some data regarding superheroes:
interface Hero {
name: string;
powers: string[];
}
const heroes = [
{
name: "Spiderman",
powers: [
"wall-crawling",
"enhanced strength",
"enhanced speed",
"spider-Sense"
]
},
{
name: "Superman",
powers: [
"flight",
"superhuman strength",
"x-ray vision",
"super-speed"
]
}
];
const hulk = {
name: "Hulk",
powers: [
"superhuman strength",
"superhuman speed",
"superhuman Stamina",
"superhuman durability"
]
};
We can now use the preceding data to create a new immutable list instance. When we add a new superhero to the list, a new immutable list is created. If we try to search for the superhero Hulk in the two immutable lists, we will observe that only the second list contains it. We can also compare both lists to observe that they are two different objects, demonstrated as follows:
const myList = new ImmutableList<Hero>(heroes);
const myList2 = myList.add(hulk);
const result1 = myList.find((h => h.name === "Hulk"));
const result2 = myList2.find((h => h.name === "Hulk"));
const areEqual = myList2 === myList;
console.log(result1); // undefined
console.log(result2); // { name: "Hulk", powers: Array(4) }
console.log(areEqual); // false
Creating our own immutable data structures is, in most cases, not necessary. In a real-world application, we can use libraries such as Immutable.js to enjoy immutable data structures.