| 1 |
# Immutable collections for JavaScript |
| 2 |
|
| 3 |
[](https://github.com/immutable-js/immutable-js/actions/workflows/ci.yml?query=branch%3Amain) [Chat on slack](https://immutable-js.slack.com) |
| 4 |
|
| 5 |
[Read the docs](https://immutable-js.com/docs/) and eat your vegetables. |
| 6 |
|
| 7 |
Docs are automatically generated from [README.md][] and [immutable.d.ts][]. |
| 8 |
Please contribute! Also, don't miss the [wiki][] which contains articles on |
| 9 |
additional specific topics. Can't find something? Open an [issue][]. |
| 10 |
|
| 11 |
**Table of contents:** |
| 12 |
|
| 13 |
- [Introduction](#introduction) |
| 14 |
- [Getting started](#getting-started) |
| 15 |
- [The case for Immutability](#the-case-for-immutability) |
| 16 |
- [JavaScript-first API](#javascript-first-api) |
| 17 |
- [Nested Structures](#nested-structures) |
| 18 |
- [Equality treats Collections as Values](#equality-treats-collections-as-values) |
| 19 |
- [Batching Mutations](#batching-mutations) |
| 20 |
- [Lazy Seq](#lazy-seq) |
| 21 |
- [Additional Tools and Resources](#additional-tools-and-resources) |
| 22 |
- [Contributing](#contributing) |
| 23 |
|
| 24 |
## Introduction |
| 25 |
|
| 26 |
[Immutable][] data cannot be changed once created, leading to much simpler |
| 27 |
application development, no defensive copying, and enabling advanced memoization |
| 28 |
and change detection techniques with simple logic. [Persistent][] data presents |
| 29 |
a mutative API which does not update the data in-place, but instead always |
| 30 |
yields new updated data. |
| 31 |
|
| 32 |
Immutable.js provides many Persistent Immutable data structures including: |
| 33 |
`List`, `Stack`, `Map`, `OrderedMap`, `Set`, `OrderedSet` and `Record`. |
| 34 |
|
| 35 |
These data structures are highly efficient on modern JavaScript VMs by using |
| 36 |
structural sharing via [hash maps tries][] and [vector tries][] as popularized |
| 37 |
by Clojure and Scala, minimizing the need to copy or cache data. |
| 38 |
|
| 39 |
Immutable.js also provides a lazy `Seq`, allowing efficient |
| 40 |
chaining of collection methods like `map` and `filter` without creating |
| 41 |
intermediate representations. Create some `Seq` with `Range` and `Repeat`. |
| 42 |
|
| 43 |
Want to hear more? Watch the presentation about Immutable.js: |
| 44 |
|
| 45 |
[](https://youtu.be/I7IdS-PbEgI) |
| 46 |
|
| 47 |
[README.md]: https://github.com/immutable-js/immutable-js/blob/main/README.md |
| 48 |
[immutable.d.ts]: https://github.com/immutable-js/immutable-js/blob/main/type-definitions/immutable.d.ts |
| 49 |
[wiki]: https://github.com/immutable-js/immutable-js/wiki |
| 50 |
[issue]: https://github.com/immutable-js/immutable-js/issues |
| 51 |
[Persistent]: https://en.wikipedia.org/wiki/Persistent_data_structure |
| 52 |
[Immutable]: https://en.wikipedia.org/wiki/Immutable_object |
| 53 |
[hash maps tries]: https://en.wikipedia.org/wiki/Hash_array_mapped_trie |
| 54 |
[vector tries]: https://hypirion.com/musings/understanding-persistent-vector-pt-1 |
| 55 |
|
| 56 |
## Getting started |
| 57 |
|
| 58 |
Install `immutable` using npm. |
| 59 |
|
| 60 |
```shell |
| 61 |
# using npm |
| 62 |
npm install immutable |
| 63 |
|
| 64 |
# using Yarn |
| 65 |
yarn add immutable |
| 66 |
|
| 67 |
# using pnpm |
| 68 |
pnpm add immutable |
| 69 |
|
| 70 |
# using Bun |
| 71 |
bun add immutable |
| 72 |
``` |
| 73 |
|
| 74 |
Then require it into any module. |
| 75 |
|
| 76 |
```js |
| 77 |
import { Map } from 'immutable'; |
| 78 |
const map1 = Map({ a: 1, b: 2, c: 3 }); |
| 79 |
const map2 = map1.set('b', 50); |
| 80 |
map1.get('b') + ' vs. ' + map2.get('b'); // 2 vs. 50 |
| 81 |
``` |
| 82 |
|
| 83 |
### Browser |
| 84 |
|
| 85 |
Immutable.js has no dependencies, which makes it predictable to include in a Browser. |
| 86 |
|
| 87 |
It's highly recommended to use a module bundler like [webpack](https://webpack.js.org/), |
| 88 |
[rollup](https://rollupjs.org/), or |
| 89 |
[browserify](https://browserify.org/). The `immutable` npm module works |
| 90 |
without any additional consideration. All examples throughout the documentation |
| 91 |
will assume use of this kind of tool. |
| 92 |
|
| 93 |
Alternatively, Immutable.js may be directly included as a script tag. Download |
| 94 |
or link to a CDN such as [CDNJS](https://cdnjs.com/libraries/immutable) |
| 95 |
or [jsDelivr](https://www.jsdelivr.com/package/npm/immutable). |
| 96 |
|
| 97 |
Use a script tag to directly add `Immutable` to the global scope: |
| 98 |
|
| 99 |
```html |
| 100 |
<script src="immutable.min.js"></script> |
| 101 |
<script> |
| 102 |
var map1 = Immutable.Map({ a: 1, b: 2, c: 3 }); |
| 103 |
var map2 = map1.set('b', 50); |
| 104 |
map1.get('b'); // 2 |
| 105 |
map2.get('b'); // 50 |
| 106 |
</script> |
| 107 |
``` |
| 108 |
|
| 109 |
Or use an AMD-style loader (such as [RequireJS](https://requirejs.org/)): |
| 110 |
|
| 111 |
```js |
| 112 |
require(['./immutable.min.js'], function (Immutable) { |
| 113 |
var map1 = Immutable.Map({ a: 1, b: 2, c: 3 }); |
| 114 |
var map2 = map1.set('b', 50); |
| 115 |
map1.get('b'); // 2 |
| 116 |
map2.get('b'); // 50 |
| 117 |
}); |
| 118 |
``` |
| 119 |
|
| 120 |
### Flow & TypeScript |
| 121 |
|
| 122 |
Use these Immutable collections and sequences as you would use native |
| 123 |
collections in your [Flowtype](https://flowtype.org/) or [TypeScript](https://typescriptlang.org) programs while still taking |
| 124 |
advantage of type generics, error detection, and auto-complete in your IDE. |
| 125 |
|
| 126 |
Installing `immutable` via npm brings with it type definitions for Flow (v0.55.0 or higher) |
| 127 |
and TypeScript (v4.5 or higher), so you shouldn't need to do anything at all! |
| 128 |
|
| 129 |
#### Using TypeScript with Immutable.js v4+ |
| 130 |
|
| 131 |
Immutable.js type definitions embrace ES2015. While Immutable.js itself supports |
| 132 |
legacy browsers and environments, its type definitions require TypeScript's 2015 |
| 133 |
lib. Include either `"target": "es2015"` or `"lib": "es2015"` in your |
| 134 |
`tsconfig.json`, or provide `--target es2015` or `--lib es2015` to the |
| 135 |
`tsc` command. |
| 136 |
|
| 137 |
```js |
| 138 |
import { Map } from 'immutable'; |
| 139 |
const map1 = Map({ a: 1, b: 2, c: 3 }); |
| 140 |
const map2 = map1.set('b', 50); |
| 141 |
map1.get('b') + ' vs. ' + map2.get('b'); // 2 vs. 50 |
| 142 |
``` |
| 143 |
|
| 144 |
#### Using TypeScript with Immutable.js v3 and earlier: |
| 145 |
|
| 146 |
Previous versions of Immutable.js include a reference file which you can include |
| 147 |
via relative path to the type definitions at the top of your file. |
| 148 |
|
| 149 |
```js |
| 150 |
///<reference path='./node_modules/immutable/dist/immutable.d.ts'/> |
| 151 |
import { Map } from 'immutable'; |
| 152 |
var map1: Map<string, number>; |
| 153 |
map1 = Map({ a: 1, b: 2, c: 3 }); |
| 154 |
var map2 = map1.set('b', 50); |
| 155 |
map1.get('b'); // 2 |
| 156 |
map2.get('b'); // 50 |
| 157 |
``` |
| 158 |
|
| 159 |
## The case for Immutability |
| 160 |
|
| 161 |
Much of what makes application development difficult is tracking mutation and |
| 162 |
maintaining state. Developing with immutable data encourages you to think |
| 163 |
differently about how data flows through your application. |
| 164 |
|
| 165 |
Subscribing to data events throughout your application creates a huge overhead of |
| 166 |
book-keeping which can hurt performance, sometimes dramatically, and creates |
| 167 |
opportunities for areas of your application to get out of sync with each other |
| 168 |
due to easy to make programmer error. Since immutable data never changes, |
| 169 |
subscribing to changes throughout the model is a dead-end and new data can only |
| 170 |
ever be passed from above. |
| 171 |
|
| 172 |
This model of data flow aligns well with the architecture of [React][] |
| 173 |
and especially well with an application designed using the ideas of [Flux][]. |
| 174 |
|
| 175 |
When data is passed from above rather than being subscribed to, and you're only |
| 176 |
interested in doing work when something has changed, you can use equality. |
| 177 |
|
| 178 |
Immutable collections should be treated as _values_ rather than _objects_. While |
| 179 |
objects represent some thing which could change over time, a value represents |
| 180 |
the state of that thing at a particular instance of time. This principle is most |
| 181 |
important to understanding the appropriate use of immutable data. In order to |
| 182 |
treat Immutable.js collections as values, it's important to use the |
| 183 |
`Immutable.is()` function or `.equals()` method to determine _value equality_ |
| 184 |
instead of the `===` operator which determines object _reference identity_. |
| 185 |
|
| 186 |
```js |
| 187 |
import { Map } from 'immutable'; |
| 188 |
const map1 = Map({ a: 1, b: 2, c: 3 }); |
| 189 |
const map2 = Map({ a: 1, b: 2, c: 3 }); |
| 190 |
map1.equals(map2); // true |
| 191 |
map1 === map2; // false |
| 192 |
``` |
| 193 |
|
| 194 |
Note: As a performance optimization Immutable.js attempts to return the existing |
| 195 |
collection when an operation would result in an identical collection, allowing |
| 196 |
for using `===` reference equality to determine if something definitely has not |
| 197 |
changed. This can be extremely useful when used within a memoization function |
| 198 |
which would prefer to re-run the function if a deeper equality check could |
| 199 |
potentially be more costly. The `===` equality check is also used internally by |
| 200 |
`Immutable.is` and `.equals()` as a performance optimization. |
| 201 |
|
| 202 |
```js |
| 203 |
import { Map } from 'immutable'; |
| 204 |
const map1 = Map({ a: 1, b: 2, c: 3 }); |
| 205 |
const map2 = map1.set('b', 2); // Set to same value |
| 206 |
map1 === map2; // true |
| 207 |
``` |
| 208 |
|
| 209 |
If an object is immutable, it can be "copied" simply by making another reference |
| 210 |
to it instead of copying the entire object. Because a reference is much smaller |
| 211 |
than the object itself, this results in memory savings and a potential boost in |
| 212 |
execution speed for programs which rely on copies (such as an undo-stack). |
| 213 |
|
| 214 |
```js |
| 215 |
import { Map } from 'immutable'; |
| 216 |
const map = Map({ a: 1, b: 2, c: 3 }); |
| 217 |
const mapCopy = map; // Look, "copies" are free! |
| 218 |
``` |
| 219 |
|
| 220 |
[React]: https://reactjs.org/ |
| 221 |
[Flux]: https://facebook.github.io/flux/docs/in-depth-overview/ |
| 222 |
|
| 223 |
## JavaScript-first API |
| 224 |
|
| 225 |
While Immutable.js is inspired by Clojure, Scala, Haskell and other functional |
| 226 |
programming environments, it's designed to bring these powerful concepts to |
| 227 |
JavaScript, and therefore has an Object-Oriented API that closely mirrors that |
| 228 |
of [ES2015][] [Array][], [Map][], and [Set][]. |
| 229 |
|
| 230 |
[es2015]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla |
| 231 |
[array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array |
| 232 |
[map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map |
| 233 |
[set]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set |
| 234 |
|
| 235 |
The difference for the immutable collections is that methods which would mutate |
| 236 |
the collection, like `push`, `set`, `unshift` or `splice`, instead return a new |
| 237 |
immutable collection. Methods which return new arrays, like `slice` or `concat`, |
| 238 |
instead return new immutable collections. |
| 239 |
|
| 240 |
```js |
| 241 |
import { List } from 'immutable'; |
| 242 |
const list1 = List([1, 2]); |
| 243 |
const list2 = list1.push(3, 4, 5); |
| 244 |
const list3 = list2.unshift(0); |
| 245 |
const list4 = list1.concat(list2, list3); |
| 246 |
assert.equal(list1.size, 2); |
| 247 |
assert.equal(list2.size, 5); |
| 248 |
assert.equal(list3.size, 6); |
| 249 |
assert.equal(list4.size, 13); |
| 250 |
assert.equal(list4.get(0), 1); |
| 251 |
``` |
| 252 |
|
| 253 |
Almost all of the methods on [Array][] will be found in similar form on |
| 254 |
`Immutable.List`, those of [Map][] found on `Immutable.Map`, and those of [Set][] |
| 255 |
found on `Immutable.Set`, including collection operations like `forEach()` |
| 256 |
and `map()`. |
| 257 |
|
| 258 |
```js |
| 259 |
import { Map } from 'immutable'; |
| 260 |
const alpha = Map({ a: 1, b: 2, c: 3, d: 4 }); |
| 261 |
alpha.map((v, k) => k.toUpperCase()).join(); |
| 262 |
// 'A,B,C,D' |
| 263 |
``` |
| 264 |
|
| 265 |
### Convert from raw JavaScript objects and arrays. |
| 266 |
|
| 267 |
Designed to inter-operate with your existing JavaScript, Immutable.js |
| 268 |
accepts plain JavaScript Arrays and Objects anywhere a method expects a |
| 269 |
`Collection`. |
| 270 |
|
| 271 |
```js |
| 272 |
import { Map, List } from 'immutable'; |
| 273 |
const map1 = Map({ a: 1, b: 2, c: 3, d: 4 }); |
| 274 |
const map2 = Map({ c: 10, a: 20, t: 30 }); |
| 275 |
const obj = { d: 100, o: 200, g: 300 }; |
| 276 |
const map3 = map1.merge(map2, obj); |
| 277 |
// Map { a: 20, b: 2, c: 10, d: 100, t: 30, o: 200, g: 300 } |
| 278 |
const list1 = List([1, 2, 3]); |
| 279 |
const list2 = List([4, 5, 6]); |
| 280 |
const array = [7, 8, 9]; |
| 281 |
const list3 = list1.concat(list2, array); |
| 282 |
// List [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] |
| 283 |
``` |
| 284 |
|
| 285 |
This is possible because Immutable.js can treat any JavaScript Array or Object |
| 286 |
as a Collection. You can take advantage of this in order to get sophisticated |
| 287 |
collection methods on JavaScript Objects, which otherwise have a very sparse |
| 288 |
native API. Because Seq evaluates lazily and does not cache intermediate |
| 289 |
results, these operations can be extremely efficient. |
| 290 |
|
| 291 |
```js |
| 292 |
import { Seq } from 'immutable'; |
| 293 |
const myObject = { a: 1, b: 2, c: 3 }; |
| 294 |
Seq(myObject) |
| 295 |
.map((x) => x * x) |
| 296 |
.toObject(); |
| 297 |
// { a: 1, b: 4, c: 9 } |
| 298 |
``` |
| 299 |
|
| 300 |
Keep in mind, when using JS objects to construct Immutable Maps, that |
| 301 |
JavaScript Object properties are always strings, even if written in a quote-less |
| 302 |
shorthand, while Immutable Maps accept keys of any type. |
| 303 |
|
| 304 |
```js |
| 305 |
import { fromJS } from 'immutable'; |
| 306 |
|
| 307 |
const obj = { 1: 'one' }; |
| 308 |
console.log(Object.keys(obj)); // [ "1" ] |
| 309 |
console.log(obj['1'], obj[1]); // "one", "one" |
| 310 |
|
| 311 |
const map = fromJS(obj); |
| 312 |
console.log(map.get('1'), map.get(1)); // "one", undefined |
| 313 |
``` |
| 314 |
|
| 315 |
Property access for JavaScript Objects first converts the key to a string, but |
| 316 |
since Immutable Map keys can be of any type the argument to `get()` is |
| 317 |
not altered. |
| 318 |
|
| 319 |
### Converts back to raw JavaScript objects. |
| 320 |
|
| 321 |
All Immutable.js Collections can be converted to plain JavaScript Arrays and |
| 322 |
Objects shallowly with `toArray()` and `toObject()` or deeply with `toJS()`. |
| 323 |
All Immutable Collections also implement `toJSON()` allowing them to be passed |
| 324 |
to `JSON.stringify` directly. They also respect the custom `toJSON()` methods of |
| 325 |
nested objects. |
| 326 |
|
| 327 |
```js |
| 328 |
import { Map, List } from 'immutable'; |
| 329 |
const deep = Map({ a: 1, b: 2, c: List([3, 4, 5]) }); |
| 330 |
console.log(deep.toObject()); // { a: 1, b: 2, c: List [ 3, 4, 5 ] } |
| 331 |
console.log(deep.toArray()); // [ 1, 2, List [ 3, 4, 5 ] ] |
| 332 |
console.log(deep.toJS()); // { a: 1, b: 2, c: [ 3, 4, 5 ] } |
| 333 |
JSON.stringify(deep); // '{"a":1,"b":2,"c":[3,4,5]}' |
| 334 |
``` |
| 335 |
|
| 336 |
### Embraces ES2015 |
| 337 |
|
| 338 |
Immutable.js supports all JavaScript environments, including legacy |
| 339 |
browsers (even IE11). However it also takes advantage of features added to |
| 340 |
JavaScript in [ES2015][], the latest standard version of JavaScript, including |
| 341 |
[Iterators][], [Arrow Functions][], [Classes][], and [Modules][]. It's inspired |
| 342 |
by the native [Map][] and [Set][] collections added to ES2015. |
| 343 |
|
| 344 |
All examples in the Documentation are presented in ES2015. To run in all |
| 345 |
browsers, they need to be translated to ES5. |
| 346 |
|
| 347 |
```js |
| 348 |
// ES2015 |
| 349 |
const mapped = foo.map((x) => x * x); |
| 350 |
// ES5 |
| 351 |
var mapped = foo.map(function (x) { |
| 352 |
return x * x; |
| 353 |
}); |
| 354 |
``` |
| 355 |
|
| 356 |
All Immutable.js collections are [Iterable][iterators], which allows them to be |
| 357 |
used anywhere an Iterable is expected, such as when spreading into an Array. |
| 358 |
|
| 359 |
```js |
| 360 |
import { List } from 'immutable'; |
| 361 |
const aList = List([1, 2, 3]); |
| 362 |
const anArray = [0, ...aList, 4, 5]; // [ 0, 1, 2, 3, 4, 5 ] |
| 363 |
``` |
| 364 |
|
| 365 |
Note: A Collection is always iterated in the same order, however that order may |
| 366 |
not always be well defined, as is the case for the `Map` and `Set`. |
| 367 |
|
| 368 |
[Iterators]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol |
| 369 |
[Arrow Functions]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions |
| 370 |
[Classes]: https://wiki.ecmascript.org/doku.php?id=strawman:maximally_minimal_classes |
| 371 |
[Modules]: https://www.2ality.com/2014/09/es6-modules-final.html |
| 372 |
|
| 373 |
## Nested Structures |
| 374 |
|
| 375 |
The collections in Immutable.js are intended to be nested, allowing for deep |
| 376 |
trees of data, similar to JSON. |
| 377 |
|
| 378 |
```js |
| 379 |
import { fromJS } from 'immutable'; |
| 380 |
const nested = fromJS({ a: { b: { c: [3, 4, 5] } } }); |
| 381 |
// Map { a: Map { b: Map { c: List [ 3, 4, 5 ] } } } |
| 382 |
``` |
| 383 |
|
| 384 |
A few power-tools allow for reading and operating on nested data. The |
| 385 |
most useful are `mergeDeep`, `getIn`, `setIn`, and `updateIn`, found on `List`, |
| 386 |
`Map` and `OrderedMap`. |
| 387 |
|
| 388 |
```js |
| 389 |
import { fromJS } from 'immutable'; |
| 390 |
const nested = fromJS({ a: { b: { c: [3, 4, 5] } } }); |
| 391 |
|
| 392 |
const nested2 = nested.mergeDeep({ a: { b: { d: 6 } } }); |
| 393 |
// Map { a: Map { b: Map { c: List [ 3, 4, 5 ], d: 6 } } } |
| 394 |
|
| 395 |
console.log(nested2.getIn(['a', 'b', 'd'])); // 6 |
| 396 |
|
| 397 |
const nested3 = nested2.updateIn(['a', 'b', 'd'], (value) => value + 1); |
| 398 |
console.log(nested3); |
| 399 |
// Map { a: Map { b: Map { c: List [ 3, 4, 5 ], d: 7 } } } |
| 400 |
|
| 401 |
const nested4 = nested3.updateIn(['a', 'b', 'c'], (list) => list.push(6)); |
| 402 |
// Map { a: Map { b: Map { c: List [ 3, 4, 5, 6 ], d: 7 } } } |
| 403 |
``` |
| 404 |
|
| 405 |
## Equality treats Collections as Values |
| 406 |
|
| 407 |
Immutable.js collections are treated as pure data _values_. Two immutable |
| 408 |
collections are considered _value equal_ (via `.equals()` or `is()`) if they |
| 409 |
represent the same collection of values. This differs from JavaScript's typical |
| 410 |
_reference equal_ (via `===` or `==`) for Objects and Arrays which only |
| 411 |
determines if two variables represent references to the same object instance. |
| 412 |
|
| 413 |
Consider the example below where two identical `Map` instances are not |
| 414 |
_reference equal_ but are _value equal_. |
| 415 |
|
| 416 |
```js |
| 417 |
// First consider: |
| 418 |
const obj1 = { a: 1, b: 2, c: 3 }; |
| 419 |
const obj2 = { a: 1, b: 2, c: 3 }; |
| 420 |
obj1 !== obj2; // two different instances are always not equal with === |
| 421 |
|
| 422 |
import { Map, is } from 'immutable'; |
| 423 |
const map1 = Map({ a: 1, b: 2, c: 3 }); |
| 424 |
const map2 = Map({ a: 1, b: 2, c: 3 }); |
| 425 |
map1 !== map2; // two different instances are not reference-equal |
| 426 |
map1.equals(map2); // but are value-equal if they have the same values |
| 427 |
is(map1, map2); // alternatively can use the is() function |
| 428 |
``` |
| 429 |
|
| 430 |
Value equality allows Immutable.js collections to be used as keys in Maps or |
| 431 |
values in Sets, and retrieved with different but equivalent collections: |
| 432 |
|
| 433 |
```js |
| 434 |
import { Map, Set } from 'immutable'; |
| 435 |
const map1 = Map({ a: 1, b: 2, c: 3 }); |
| 436 |
const map2 = Map({ a: 1, b: 2, c: 3 }); |
| 437 |
const set = Set().add(map1); |
| 438 |
set.has(map2); // true because these are value-equal |
| 439 |
``` |
| 440 |
|
| 441 |
Note: `is()` uses the same measure of equality as [Object.is][] for scalar |
| 442 |
strings and numbers, but uses value equality for Immutable collections, |
| 443 |
determining if both are immutable and all keys and values are equal |
| 444 |
using the same measure of equality. |
| 445 |
|
| 446 |
[object.is]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is |
| 447 |
|
| 448 |
#### Performance tradeoffs |
| 449 |
|
| 450 |
While value equality is useful in many circumstances, it has different |
| 451 |
performance characteristics than reference equality. Understanding these |
| 452 |
tradeoffs may help you decide which to use in each case, especially when used |
| 453 |
to memoize some operation. |
| 454 |
|
| 455 |
When comparing two collections, value equality may require considering every |
| 456 |
item in each collection, on an `O(N)` time complexity. For large collections of |
| 457 |
values, this could become a costly operation. Though if the two are not equal |
| 458 |
and hardly similar, the inequality is determined very quickly. In contrast, when |
| 459 |
comparing two collections with reference equality, only the initial references |
| 460 |
to memory need to be compared which is not based on the size of the collections, |
| 461 |
which has an `O(1)` time complexity. Checking reference equality is always very |
| 462 |
fast, however just because two collections are not reference-equal does not rule |
| 463 |
out the possibility that they may be value-equal. |
| 464 |
|
| 465 |
#### Return self on no-op optimization |
| 466 |
|
| 467 |
When possible, Immutable.js avoids creating new objects for updates where no |
| 468 |
change in _value_ occurred, to allow for efficient _reference equality_ checking |
| 469 |
to quickly determine if no change occurred. |
| 470 |
|
| 471 |
```js |
| 472 |
import { Map } from 'immutable'; |
| 473 |
const originalMap = Map({ a: 1, b: 2, c: 3 }); |
| 474 |
const updatedMap = originalMap.set('b', 2); |
| 475 |
updatedMap === originalMap; // No-op .set() returned the original reference. |
| 476 |
``` |
| 477 |
|
| 478 |
However updates which do result in a change will return a new reference. Each |
| 479 |
of these operations occur independently, so two similar updates will not return |
| 480 |
the same reference: |
| 481 |
|
| 482 |
```js |
| 483 |
import { Map } from 'immutable'; |
| 484 |
const originalMap = Map({ a: 1, b: 2, c: 3 }); |
| 485 |
const updatedMap = originalMap.set('b', 1000); |
| 486 |
// New instance, leaving the original immutable. |
| 487 |
updatedMap !== originalMap; |
| 488 |
const anotherUpdatedMap = originalMap.set('b', 1000); |
| 489 |
// Despite both the results of the same operation, each created a new reference. |
| 490 |
anotherUpdatedMap !== updatedMap; |
| 491 |
// However the two are value equal. |
| 492 |
anotherUpdatedMap.equals(updatedMap); |
| 493 |
``` |
| 494 |
|
| 495 |
## Batching Mutations |
| 496 |
|
| 497 |
> If a tree falls in the woods, does it make a sound? |
| 498 |
> |
| 499 |
> If a pure function mutates some local data in order to produce an immutable |
| 500 |
> return value, is that ok? |
| 501 |
> |
| 502 |
> — Rich Hickey, Clojure |
| 503 |
|
| 504 |
Applying a mutation to create a new immutable object results in some overhead, |
| 505 |
which can add up to a minor performance penalty. If you need to apply a series |
| 506 |
of mutations locally before returning, Immutable.js gives you the ability to |
| 507 |
create a temporary mutable (transient) copy of a collection and apply a batch of |
| 508 |
mutations in a performant manner by using `withMutations`. In fact, this is |
| 509 |
exactly how Immutable.js applies complex mutations itself. |
| 510 |
|
| 511 |
As an example, building `list2` results in the creation of 1, not 3, new |
| 512 |
immutable Lists. |
| 513 |
|
| 514 |
```js |
| 515 |
import { List } from 'immutable'; |
| 516 |
const list1 = List([1, 2, 3]); |
| 517 |
const list2 = list1.withMutations(function (list) { |
| 518 |
list.push(4).push(5).push(6); |
| 519 |
}); |
| 520 |
assert.equal(list1.size, 3); |
| 521 |
assert.equal(list2.size, 6); |
| 522 |
``` |
| 523 |
|
| 524 |
Note: Immutable.js also provides `asMutable` and `asImmutable`, but only |
| 525 |
encourages their use when `withMutations` will not suffice. Use caution to not |
| 526 |
return a mutable copy, which could result in undesired behavior. |
| 527 |
|
| 528 |
_Important!_: Only a select few methods can be used in `withMutations` including |
| 529 |
`set`, `push` and `pop`. These methods can be applied directly against a |
| 530 |
persistent data-structure where other methods like `map`, `filter`, `sort`, |
| 531 |
and `splice` will always return new immutable data-structures and never mutate |
| 532 |
a mutable collection. |
| 533 |
|
| 534 |
## Lazy Seq |
| 535 |
|
| 536 |
`Seq` describes a lazy operation, allowing them to efficiently chain |
| 537 |
use of all the higher-order collection methods (such as `map` and `filter`) |
| 538 |
by not creating intermediate collections. |
| 539 |
|
| 540 |
**Seq is immutable** — Once a Seq is created, it cannot be |
| 541 |
changed, appended to, rearranged or otherwise modified. Instead, any mutative |
| 542 |
method called on a `Seq` will return a new `Seq`. |
| 543 |
|
| 544 |
**Seq is lazy** — `Seq` does as little work as necessary to respond to any |
| 545 |
method call. Values are often created during iteration, including implicit |
| 546 |
iteration when reducing or converting to a concrete data structure such as |
| 547 |
a `List` or JavaScript `Array`. |
| 548 |
|
| 549 |
For example, the following performs no work, because the resulting |
| 550 |
`Seq`'s values are never iterated: |
| 551 |
|
| 552 |
```js |
| 553 |
import { Seq } from 'immutable'; |
| 554 |
const oddSquares = Seq([1, 2, 3, 4, 5, 6, 7, 8]) |
| 555 |
.filter((x) => x % 2 !== 0) |
| 556 |
.map((x) => x * x); |
| 557 |
``` |
| 558 |
|
| 559 |
Once the `Seq` is used, it performs only the work necessary. In this |
| 560 |
example, no intermediate arrays are ever created, filter is called three |
| 561 |
times, and map is only called once: |
| 562 |
|
| 563 |
```js |
| 564 |
oddSquares.get(1); // 9 |
| 565 |
``` |
| 566 |
|
| 567 |
Any collection can be converted to a lazy Seq with `Seq()`. |
| 568 |
|
| 569 |
```js |
| 570 |
import { Map, Seq } from 'immutable'; |
| 571 |
const map = Map({ a: 1, b: 2, c: 3 }); |
| 572 |
const lazySeq = Seq(map); |
| 573 |
``` |
| 574 |
|
| 575 |
`Seq` allows for the efficient chaining of operations, allowing for the |
| 576 |
expression of logic that can otherwise be very tedious: |
| 577 |
|
| 578 |
```js |
| 579 |
lazySeq |
| 580 |
.flip() |
| 581 |
.map((key) => key.toUpperCase()) |
| 582 |
.flip(); |
| 583 |
// Seq { A: 1, B: 2, C: 3 } |
| 584 |
``` |
| 585 |
|
| 586 |
As well as expressing logic that would otherwise seem memory or time |
| 587 |
limited, for example `Range` is a special kind of Lazy sequence. |
| 588 |
|
| 589 |
```js |
| 590 |
import { Range } from 'immutable'; |
| 591 |
Range(1, Infinity) |
| 592 |
.skip(1000) |
| 593 |
.map((n) => -n) |
| 594 |
.filter((n) => n % 2 === 0) |
| 595 |
.take(2) |
| 596 |
.reduce((r, n) => r * n, 1); |
| 597 |
// 1006008 |
| 598 |
``` |
| 599 |
|
| 600 |
## Comparison of filter(), groupBy(), and partition() |
| 601 |
|
| 602 |
The `filter()`, `groupBy()`, and `partition()` methods are similar in that they |
| 603 |
all divide a collection into parts based on applying a function to each element. |
| 604 |
All three call the predicate or grouping function once for each item in the |
| 605 |
input collection. All three return zero or more collections of the same type as |
| 606 |
their input. The returned collections are always distinct from the input |
| 607 |
(according to `===`), even if the contents are identical. |
| 608 |
|
| 609 |
Of these methods, `filter()` is the only one that is lazy and the only one which |
| 610 |
discards items from the input collection. It is the simplest to use, and the |
| 611 |
fact that it returns exactly one collection makes it easy to combine with other |
| 612 |
methods to form a pipeline of operations. |
| 613 |
|
| 614 |
The `partition()` method is similar to an eager version of `filter()`, but it |
| 615 |
returns two collections; the first contains the items that would have been |
| 616 |
discarded by `filter()`, and the second contains the items that would have been |
| 617 |
kept. It always returns an array of exactly two collections, which can make it |
| 618 |
easier to use than `groupBy()`. Compared to making two separate calls to |
| 619 |
`filter()`, `partition()` makes half as many calls it the predicate passed to |
| 620 |
it. |
| 621 |
|
| 622 |
The `groupBy()` method is a more generalized version of `partition()` that can |
| 623 |
group by an arbitrary function rather than just a predicate. It returns a map |
| 624 |
with zero or more entries, where the keys are the values returned by the |
| 625 |
grouping function, and the values are nonempty collections of the corresponding |
| 626 |
arguments. Although `groupBy()` is more powerful than `partition()`, it can be |
| 627 |
harder to use because it is not always possible predict in advance how many |
| 628 |
entries the returned map will have and what their keys will be. |
| 629 |
|
| 630 |
| Summary | `filter` | `partition` | `groupBy` | |
| 631 |
| :---------------------------- | :------- | :---------- | :------------- | |
| 632 |
| ease of use | easiest | moderate | hardest | |
| 633 |
| generality | least | moderate | most | |
| 634 |
| laziness | lazy | eager | eager | |
| 635 |
| # of returned sub-collections | 1 | 2 | 0 or more | |
| 636 |
| sub-collections may be empty | yes | yes | no | |
| 637 |
| can discard items | yes | no | no | |
| 638 |
| wrapping container | none | array | Map/OrderedMap | |
| 639 |
|
| 640 |
## Additional Tools and Resources |
| 641 |
|
| 642 |
- [Atom-store](https://github.com/jameshopkins/atom-store/) |
| 643 |
|
| 644 |
- A Clojure-inspired atom implementation in Javascript with configurability |
| 645 |
for external persistance. |
| 646 |
|
| 647 |
- [Chai Immutable](https://github.com/astorije/chai-immutable) |
| 648 |
|
| 649 |
- If you are using the [Chai Assertion Library](https://chaijs.com/), this |
| 650 |
provides a set of assertions to use against Immutable.js collections. |
| 651 |
|
| 652 |
- [Fantasy-land](https://github.com/fantasyland/fantasy-land) |
| 653 |
|
| 654 |
- Specification for interoperability of common algebraic structures in JavaScript. |
| 655 |
|
| 656 |
- [Immutagen](https://github.com/pelotom/immutagen) |
| 657 |
|
| 658 |
- A library for simulating immutable generators in JavaScript. |
| 659 |
|
| 660 |
- [Immutable-cursor](https://github.com/redbadger/immutable-cursor) |
| 661 |
|
| 662 |
- Immutable cursors incorporating the Immutable.js interface over |
| 663 |
Clojure-inspired atom. |
| 664 |
|
| 665 |
- [Immutable-ext](https://github.com/DrBoolean/immutable-ext) |
| 666 |
|
| 667 |
- Fantasyland extensions for immutablejs |
| 668 |
|
| 669 |
- [Immutable-js-tools](https://github.com/madeinfree/immutable-js-tools) |
| 670 |
|
| 671 |
- Util tools for immutable.js |
| 672 |
|
| 673 |
- [Immutable-Redux](https://github.com/gajus/redux-immutable) |
| 674 |
|
| 675 |
- redux-immutable is used to create an equivalent function of Redux |
| 676 |
combineReducers that works with Immutable.js state. |
| 677 |
|
| 678 |
- [Immutable-Treeutils](https://github.com/lukasbuenger/immutable-treeutils) |
| 679 |
|
| 680 |
- Functional tree traversal helpers for ImmutableJS data structures. |
| 681 |
|
| 682 |
- [Irecord](https://github.com/ericelliott/irecord) |
| 683 |
|
| 684 |
- An immutable store that exposes an RxJS observable. Great for React. |
| 685 |
|
| 686 |
- [Mudash](https://github.com/brianneisler/mudash) |
| 687 |
|
| 688 |
- Lodash wrapper providing Immutable.JS support. |
| 689 |
|
| 690 |
- [React-Immutable-PropTypes](https://github.com/HurricaneJames/react-immutable-proptypes) |
| 691 |
|
| 692 |
- PropType validators that work with Immutable.js. |
| 693 |
|
| 694 |
- [Redux-Immutablejs](https://github.com/indexiatech/redux-immutablejs) |
| 695 |
|
| 696 |
- Redux Immutable facilities. |
| 697 |
|
| 698 |
- [Rxstate](https://github.com/yamalight/rxstate) |
| 699 |
|
| 700 |
- Simple opinionated state management library based on RxJS and Immutable.js. |
| 701 |
|
| 702 |
- [Transit-Immutable-js](https://github.com/glenjamin/transit-immutable-js) |
| 703 |
- Transit serialisation for Immutable.js. |
| 704 |
- See also: [Transit-js](https://github.com/cognitect/transit-js) |
| 705 |
|
| 706 |
Have an additional tool designed to work with Immutable.js? |
| 707 |
Submit a PR to add it to this list in alphabetical order. |
| 708 |
|
| 709 |
## Contributing |
| 710 |
|
| 711 |
Use [Github issues](https://github.com/immutable-js/immutable-js/issues) for requests. |
| 712 |
|
| 713 |
We actively welcome pull requests, learn how to [contribute](https://github.com/immutable-js/immutable-js/blob/main/.github/CONTRIBUTING.md). |
| 714 |
|
| 715 |
Immutable.js is maintained within the [Contributor Covenant's Code of Conduct](https://www.contributor-covenant.org/version/2/0/code_of_conduct/). |
| 716 |
|
| 717 |
### Changelog |
| 718 |
|
| 719 |
Changes are tracked as [Github releases](https://github.com/immutable-js/immutable-js/releases). |
| 720 |
|
| 721 |
### License |
| 722 |
|
| 723 |
Immutable.js is [MIT-licensed](./LICENSE). |
| 724 |
|
| 725 |
### Thanks |
| 726 |
|
| 727 |
[Phil Bagwell](https://www.youtube.com/watch?v=K2NYwP90bNs), for his inspiration |
| 728 |
and research in persistent data structures. |
| 729 |
|
| 730 |
[Hugh Jackson](https://github.com/hughfdjackson/), for providing the npm package |
| 731 |
name. If you're looking for his unsupported package, see [this repository](https://github.com/hughfdjackson/immutable). |