Book Image

Mastering Immutable.js

By : Adam Boduch
Book Image

Mastering Immutable.js

By: Adam Boduch

Overview of this book

Immutable.js is a JavaScript library that will improve the robustness and dependability of your larger JavaScript projects. All aspects of the Immutable.js framework are covered in this book, and common JavaScript situations are examined in a hands-on way so that you gain practical experience using Immutable.js that you can apply across your own JavaScript projects. The key to building robust JavaScript applications using immutability is to control how data flows through your application, and how the side-effects of these flows are managed. Many problems that are difficult to pinpoint in large codebases stem from data that’s been mutated where it shouldn’t have been. With immutable data, you rule out an entire class of bugs. Mastering Immutable.js takes a practical, hands-on approach throughout, and shows you the ins and outs of the Immutable.js framework so that you can confidently build successful and dependable JavaScript projects.
Table of Contents (23 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Adding values to collections


The two main collection types on which we'll call persistent change methods are lists and maps. When you call a method to add a new value to a collection, you have to store the result somewhere because persistent changes only create data; they never destroy data.

Pushing values to lists

You can push a new value onto a list using the push() method, as follows:

const myList = List.of(1, 2, 3);
const myChangedList = myList.push(4);

console.log('myList', myList.toJS());
// -> myList [ 1, 2, 3 ]
console.log('myChangedList', myChangedList.toJS());
// -> myChangedList [ 1, 2, 3, 4 ]

The end result of calling push(4) is a new list. If you want to make use of this list, you have to store it somewhere. In this example, we just want to print the JSON representation of the list, and as you can see, 4 is added to myChangedList. You can also see that the contents of myList haven't changed. Of course not—it's immutable!

Adding key-value pairs to maps

With maps, we use the...