37,19 €
This book shows JavaScript developers how to build highly dependable JavaScript projects using the Immutable.js framework.
This book is for JavaScript developers, from intermediate level and beyond, who need to create dependable JavaScript projects, using the Immutable.js JavaScript framework.
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.
Adam Boduch covers all the key concepts and benefits of immutability, and then presents you with hands-on practical experience on implementing immutability in your JavaScript projects.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 217
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: September 2017
Production reference: 1250917
ISBN 978-1-78839-511-3
www.packtpub.com
Author
Adam Boduch
Technical Editor
Joel Wilfred D'souza
Reviewer
Jurgen Van de Moere
Project Editor
Suzanne Coutinho
Acquisition Editor
Dominic Shakeshaft
Proofreader
Safis Editing
Content Development Editor
Gary Shwartz
Production Coordinator
Arvindkumar Gupta
Copy Editor
Tom Jacob
Adam Boduch has been involved with large-scale JavaScript development for nearly 10 years. Before moving to the frontend, he worked on several large-scale cloud computing products, using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.He is the author of several JavaScript books, including React and React Native by Packt Publishing and is passionate about innovative user experiences and high performance.
Jurgen Van de Moere is a front-end architect based in Belgium. He began his career in 1999 and worked for more than a decade as a web developer and system engineer for large companies across Europe. In 2012, driven by his passion for Web Technologies, Jurgen decided to specialise in JavaScript and Angular. Since then, he has helped many leading businesses succeed in building secure, maintainable, testable, and scalable Angular applications. In his mission to continually share his knowledge with others, Jurgen serves as a private advisor and mentor to world-renowned businesses and developers around the world.
You won't find Jurgen in the spotlight very often as he loves to spend time with his family, reading books and writing articles. His writings impact thousands of developers a day and are regularly featured by some of the leading publishers in the tech industry.
Jurgen is actively involved in growing the Belgian Angular community as co-organizer of NG-BE, Belgium's first ever Angular conference. In 2016, he was awarded through the Google GDE program as the first ever Google Developer Expert in Belgium for web technologies. You can reach Jurgen at [email protected], follow him on Twitter at https://twitter.com/jvandemo, or read his articles on https://jvandemo.com.
For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review.
If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Why Immutable.js?
Mutations are destructive
Deleting old data
A scary class of bugs
Persisting changes
The Immutable.js approach
A collections API
Collection methods return new data
Chaining method calls
Unidirectional data flow
What other direction is there?
Subscriptions are out
Data is only created
Implicit side-effects are hard to do
Other libraries similar to Immutable.js
What are we comparing?
Lodash is a good bet
Summary
Creating Immutable Data
Immutable.js constructors
The types of Immutable.js data
Lists
Maps
Ordered maps
Sets
Ordered sets
Sequences
Stacks
Records
Passing JavaScript collections
Passing Immutable.js collections
Using the of() method
Lists of values
Maps of values
Sets of values
Sequences of values
Parsing data using the fromJS() function
Parsing JavaScript arrays
Parsing JavaScript objects
Parsing complex structures
Summary
Persistent Changes
Adding values to collections
Pushing values to lists
Adding key-value pairs to maps
Chaining value insertion methods
Pushing multiple list values
Adding multiple map key-value pairs
Changing collection values
Changing list values
Setting list values
Updating list values
Changing map values
Setting map values
Updating map values
Chaining collection mutation methods
Removing values from collections
Removing values from lists
Removing values from maps
Chaining collection removal methods
Emptying collections
Replacing collections with new instances
Using the clear() method
Keeping track of changes
Summary
Filtering Collections and Finding Items
Filtering using simple comparisons
Strict equality
Greater than and less than
Filtering by negation
Filtering maps by keys
Filtering string keys
Filtering fancy keys
Finding collection values
Value existence checks
Getting values using find()
Filtering using deep equality
Using the is() function and the equals() method
Searching lists of maps
Partial matches
The shape of maps
Subsets and supersets
Changing the search direction
Searching sorted collections
Using findLast() and reduceRight()
Summary
Sequences and Side-Effects
Why lazy evaluation?
Large collections are expensive
Avoiding unnecessary work
Chained operations are easy to understand
Sequence creation and iteration
Basic sequence creation
Collections to sequences
Lists to sequences
Maps to sequences
Iterating with for...of loops
Iterating with forEach()
Lazy filtering
Basic lazy filtering
Multiple filter levels
Limiting results and reducing work
Using take() to limit results
Using slice() to paginate
Summary
Sorting Collections
Sorting and reversing
The sort() method
The reverse() method
Sorting lists of maps
The sortBy() method
Sorting by multiple keys
Ordered maps
Order guarantees
Insertion order is not sort order
Setting the order with set()
Sorting maps
Creating ordered maps
Sorting maps by key
Maintaining sort order
Finding the insertion index
Is this really necessary?
Summary
Mapping and Reducing
Mapping lists of maps
Plucking values
Computing new values
Mapping to new lists of maps
Creating new keys
Filtering keys
Reducing collections
When filtering isn't enough
Producing minimums and maximums
Accumulating values
Lazy mapping
Multiple map() calls
Filtering before mapping
The ultimate lazy pattern
Summary
Zipping and Flattening
Zipping collections
Removing excess iterations
Zipping lists of simple values
Zipping lists of maps
Lazy zipping
Flattening collections
Avoiding recursion
Deep flattening nested lists
Shallow flattening lists
Flattening nested maps
Summary
Persistent Change Detection
Collection equality
Strict equality and mutative methods
Detecting changes
Detecting no changes
Strict equality versus deep equality
Transformations versus mutations
Transformations always return new collections
Detecting changes before transformations
Caching side-effects
Summary
Working with Sets
Sets are not lists
Do not use the get() method
No defined iteration order
Maps with keys only
Removing duplicates
Converting to sets
Converting to sets, then back to lists
Lazy duplicate removal
Ordered sets
Sorting sets
Iterating over sets
Maintaining sets
Adding unique values
Adding duplicate values
Summary
Comparing Collections
Set intersections
Intersecting sets
Ordered intersections
List intersections
Reducing list intersections
Filtering list intersections
Collection differences
Set differences
List differences
Comparing maps
Map intersections
Map differences
Subsets and supersets
List subsets
List supersets
Summary
Combining Collections
Merging maps
Merging maps by key
Merging maps with complex keys
Merging lists
Merging simple values
Merging lists of maps
Merging lists of lists
Concatenating lists and sequences
Simple value concatenation
Lazy sequence concatenation
Interposing and interleaving
Lazily interposing values
Lazily interleaving values
Summary
Declarative Decision Making
Mapping behavior
Keys are logical paths, values are behavior
Wrapping behavior maps in functions
Parameters and defaults
Providing default behavior
Parameterizing mapped behavior
Composing behavior
A generic higher-order behavior function
Logical and/or conditions
Complex behavior compositions
Summary
Side-Effects in User Interfaces
A simple application
Application data
Filter controls
Episode results
DOM side-effects
HTML markup
Filter fields
Rating slider
Episode template
Filtering episodes
Handling events
Rendering elements
React side-effects
Application state
Handling events and changing state
Mapping episodes to elements
Summary
Side-Effects in Node.js
Reading data into collections
Reading and parsing CSV data
Reading large amounts of data
Using concat()
Using push()
Using push() and withMutations()
Writing collection data
Iterating over collections and writing lines
Asynchronous data and sequences
Chaining lazy sequences and streams
Summary
Immutable Architecture
The reusable application state updater
Initial state
Side-effects
Updating state and running side-effects
Initial application state
Result state
Creating a new episode state
Events and state updaters
Updating the search query
Updating the checkboxes and slider state
Updating new episode data
Creating new episodes
Executing side-effects
Rendering episode results
Rendering the result count
Resetting the new episode form
Summary
I like functional programming languages. One of my favorite features is native immutability. Some functional languages, by default, don't let you change values. What's amazing about this capability is that you can't accidentally break your application by mutating data at the wrong time. If you try, the code won't even compile.
I also dislike certain aspects of functional programming languages. On one hand, it's great that immutability is enforced the way it is. On the other hand, there are times when I just need to push aside my functional programming principles and get the job done.
The JavaScript language has many useful functional programming features out of the box. You don't need a library to compose higher-order functions, for example. Something that's difficult to get right with JavaScript is immutability. This is where Immutable.js shines.
When I first heard about Immutable.js, I pictured a library that enforced immutability on JavaScript structures and nothing more. It turns out there's much more. When you're working with immutable structures, you're constantly creating them. The Immutable.js collection API helps you create the structures you need, when you need them.
Since this is a JavaScript library, there's no immutability by default. This allows me to use Immutable.js where immutability matters, and to mutate things when I need to. This is what makes this such an essential library for applications in the real world; pragmatic functional programming that gets the job done.
Chapter 1, Why Immutable.js?, explains why you want to use this library.
Chapter 2, Creating Immutable Data, helps you get started by creating immutable collections.
Chapter 3, Persistent Changes, discusses how to create new data by changing existing data.
Chapter 4, Filtering Collections and Finding Items, talks about locating the data that you need.
Chapter 5, Sequences and Side-Effects, explains how to iterate over collections in order to use collection data.
Chapter 6, Sorting Collections, helps you in get the order right.
Chapter 7, Mapping and Reducing, introduces the fundamentals of transforming collection data.
Chapter 8, Zipping and Flattening, discusses simplifying iterations and collection structures.
Chapter 9, Persistent Change Detection, enables you to determine whether a persistent change method actually changed data.
Chapter 10, Working with Sets, explains how to produce unique collection values.
Chapter 11, Comparing Collections, talks about figuring out how one collection relates to another.
Chapter 12, Combining Collections, helps you build new collections by adding collections together.
Chapter 13, Declarative Decision Making, uses immutable collections to help write declarative code.
Chapter 14, Side-Effects in User Interfaces, explains rendering UI components with immutable collections.
Chapter 15, Side-Effects in Node.js, discusses reading and writing collection data using IO streams.
Chapter 16, Immutable Architecture, puts it all together, in the form of a reusable pattern.
You need a computer, Node.js, and a code editor. Instructions for setting up tools to run the code examples can be found at https://github.com/PacktPublishing/Mastering-Immutablejs.
This book is for anyone who wants to improve the reliability and performance of their JavaScript code by leveraging the ideas of immutability. Basic JavaScript knowledge is assumed. You should be able to create arrays and objects, manipulate arrays and objects, and create and call functions.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you. You can download the code files by following these steps:
Log in or register to our website using your email address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-Immutablejs. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/MasteringImmutablejs.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
Immutable.js is yet another JavaScript library. If this makes you cringe, don't worry—I feel your pain. The last thing that JavaScript developers need is another library to learn. Then, I used the library and realized that Immutable.js is one of those gems that you don't have to feel bad about including as a dependency.
This first chapter will show you what Immutable.js is all about. Hopefully, I can dispel any mysteries about Immutable.js while making you want to try it out for yourself.
Here's what you'll learn in this chapter before getting your hands dirty in the chapters that follow:
Why changes to data are destructive
What are persistent changes?
The hybrid functional/object approach used by Immutable.js
Why data flows in one direction in
Immutable.js
Alternative libraries and approaches to immutability
When you mutate data, you change it. If data is immutable, you can't change it.
Immutability is native to some programming languages. But why is changing data bad, and how does one write software with data that never changes?
When you first learned how to program, one of the earliest concepts that you were taught was the variable. A variable is something that's used to store a value, so of course it's important! When you create a variable and assign its initial value, it feels like you're creating new data. This is because you are creating new data.
Then, later on in your code, you assign a new value to your variable. It's a variable, so naturally it varies. This might also seem like you're creating new data, which you are; if you assign the value 5 to your variable, then that's a new value that didn't exist before. Here's the catch: you're also destroying data. What if your variable had a value of 2 before you assigned it 5?
This might not seem like a big deal. Isn't a variable supposed to store whatever value you assign to it? Yes, variables work perfectly fine that way. They do exactly what we ask them to do. So, the problem isn't strictly that variables can change their values. Rather, it's a human limitation—we can't reason our way through the huge number of variable changes that happen in our code. This leads to some scary bugs.
Imagine that you're trying to bake a loaf of bread. Nothing fancy, just a plain loaf. You don't even need to look at the recipe—it's just a handful of ingredients, and you've memorized the steps. Now suppose that one or two of your ingredients have been changed without your knowledge. You still follow the steps, and the end result still looks like bread, but then your family eats it. One family member says something tastes off, another doesn't seem to notice anything, while yet another heads straight for the washroom.
These are just some of many possible scenarios that could have played out, and the problems all stemmed from the ingredients used. In other words, because the ingredients were allowed to change, they did change. Consider the game Telephone. In this game, there is a line of people and a message is whispered to the first person in the line. The same message is whispered (allegedly) to the next person, and so on, until the message reaches the last person who then says the message out loud. The ending message is almost never the same as the starting message. Once again, the message changes because it's allowed to change.
When writing software, you're no different from the person making bread using incorrect ingredients or the Telephone game player relaying an incorrect message. The end result is a scary type of bug. If you mess up your bread, can you pinpoint exactly what went wrong? Can you identify the Telephone game players who broke the message? Your variables change because they can. You've written code to make the variables change, and sometimes everything works exactly as you want it to. But when something goes wrong, it's very difficult to figure out what went wrong.
If data isn't supposed to change, just how are we supposed to get anything done? How do we move the state of an application along from one state to the next if our data is immutable? The answer is that every operation that you perform on immutable data creates new immutable data. These are called persistent changes, because the original data is persisted. The new data that's created as a result of running the operation contains the changes. When we call an operation on this new data, it returns new data, and so on.
What are we supposed to do with the old data when we make a persistent change that results in new data? The answer is – it depends. Sometimes, you'll just replace the old data with the new data. Yes, the variable is changed, but it's replaced with an entirely new reference. This means that something that is still referencing the old data is never affected by your persistent changes.
Different JavaScript libraries each have their own approach to deal with certain things. For example, React relies on JSX—an XML dialect embedded in JavaScript for declaring user interface components. Lodash exposes lots of little functions, some of which can be chained together to simplify complex code. The idea behind Immutable.js is to expose a small number of collection classes as its API. How does it work?
A collection in JavaScript refers to anything that can be iterated over, for example, when using a for..of