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

Sorting and reversing


Just like the native JavaScript array, Immutable.js collections have a sort() method. Instead of sorting the values in place like an array, this results in a new collection.

The sort() method

Sorting lists is just like sorting native JavaScript arrays, except that you end up with a new list. The sort() method takes a comparator function, which is used to compare two collection values. If you don't provide this argument, the default comparator uses greater than and less than operators since this is the most common way to sort values:

const myList = List.of(2, 1, 4, 3);
const mySortedList = myList.sort();

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

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

As you can see, the new list of numbers is created and it is sorted numerically.

Note

Sorting is one operation that can't be performed lazily, since you have to go through every item in the collection before you know...