Immutable.js – permanent protection from change

Immutable.js, with its home page at http://facebook.github.io/immutable-js and a tagline of Immutable collections for JavaScript, was originally named for persistence. Then it went through a name change to something that would register more quickly by referring to the immutable. Immutable.js plugs a gap in JavaScript as a functional language and offers significantly more functional-friendly data structures for collections (which is the point for which it was created).

It offers data structures for collections that are immutable. They support the creation of modified copies gracefully enough, but it is always the copy that is changed, never the original. Though this is more of a minor point, it greatly reduces the need for "defensive copying" and related workarounds for not using immutable data where there are multiple programmers. The original code could be chugging along with a different and modified copy of the data structure that you want, but your copy, which you have kept as a reference, is guaranteed to be entirely untouched. The library is intended to support other niceties, such as easy conversion to and from staple JavaScript data structures.

However, data structures of Immutable.js are not only immutable; they are also lazy in some aspects, and the document clearly marks which aspects of an application are eager. (as a reminder, lazy data structures are treated in a print-on-demand fashion when needed, while eager operations are done at once and upfront). Furthermore, certain functional idioms are baked into Immutable.js facilities. For instance, there is a .take(n) method offered. It returns the first n items of a list in the classic functional fashion. Other functional staples, such as map(), filter(), and reduce(), are also available. In general, runtime complexity is as good as a computer scientist could reasonably request.

There are several data types provided by Immutable.js; these include the following (the descriptions in this and the next table are partly based on the official documentation):

Immutable.js class

Description

Collection

This is an abstract base class for Immutable.js data structures. It cannot be directly instantiated.

IndexedCollection

A collection that represents indexed values in a particular order.

IndexedIterable

This is an iterable with indexed numeric keys that support some array-like interface features, such as indexOf() (An iterable is something that you can iterate through like a list, but it may or may not be a list in the internals).

IndexedSeq

A Seq that supports an ordered indexed list of values.

Iterable

A set of (key and index) values that can be iterated through. This class is the base class for all collections.

KeyedCollection

A collection that represents key-value pairs.

KeyedIterable

An iterable with discrete keys tied to each iterable.

KeyedSeq

A sequence that represents key-value pairs.

List

An ordered collection, somewhat like a (dense) JavaScript array.

Map

A keyed iterable of key-value pairs.

OrderedMap

A map that does everything that a map does and, in addition, guarantees that iterations will produce keys in the order in which they are set.

OrderedSet

A set that does everything that a set does and, in addition, guarantees, that iterations will produce values in the order in which they are set.

Record

A class that produces concrete records. Conceptually, this is different from the other records here. The other elements are, conceptually, collections of "whatnots," perhaps objects that have a similar structure. The Record class is closer to the records one encounters in school, where one record is similar to a row in a database table, while result sets or tables are more like container objects.

Seq

A sequence of values, which may or may not be backed by a concrete data structure.

Set

A collection of unique values.

SetCollection

A collection of values without keys or indices.

SetIterable

Iterables representing values without keys or indices.

SetSeq

A sequence representing a set of values.

Stack

A standard stack with push() and pop(). Semantics always go to first element, unlike JavaScript arrays.

Note

Record is slightly different from the others; it is similar to a JavaScript object that meets certain criteria. The other elements are related container classes that provide functional access to some collection of objects and tend to have a similar list of methods supported.

The methods for List, to pick one example, include the following:

Immutable.List method

Description

asImmutable

A function that takes a (mutable) JavaScript collection and renders an Immutable.js collection.

asMutable

This is a concession to "not-the-best" programming. The proper way to handle mutations based on an Immutable.js collection is to use with Mutations. Even if asMutable is available, it should only be used inside of functions and never be made available or returned.

butLast

This produces a similar new List, but it lacks the last entry.

concat

Concatenate (that is, append) two iterables of the same type.

contains

This is true if the value exists in this List.

count

Return the size of this List.

countBy

Group the List's contents with a grouper function, and then emit counts for the keys as partitioned by the grouper.

delete

Create a new List without this key.

deleteIn

Remove a key from a keypath, which allows traversal from an outer collection to an inner collection, much like the way a filesystem path allows traversal of the filesystem from an outer directory to an inner directory.

entries

An iteration of the List as key, value tuples.

entrySeq

Create a new IndexedSeq of key, value tuples.

equals

This is a full equality comparison.

every

This is true if a predicate is true for all entries in this List.

filter

Returns the elements of a List for which the provided predicate holds true.

filterNot

Returns the elements of a List for which the provided predicate returns false.

find

Returns the value for which the provided predicate holds true.

findIndex

Returns the first index for which the provided predicate holds true.

findLast

Returns the last element for which the provided predicate holds true.

findLastIndex

Returns the last index for which the provided predicate holds true.

first

The first value in the List.

flatMap

This flat-maps, or collapses, a potential List of Lists into a List that is one deep.

flatten

This flattens nested iterables.

forEach

Executes a function for each entry in the list.

fromEntrySeq

Return a KeyedSeq of any iterable of the key, value tuples.

get

Returns the value for a key.

getIn

Traverses a key path (like a filesystem path) to get a key, if available.

groupBy

Converts a List into a List of Lists keyed by the grouping of a provided grouper function.

has

This is true if a key exists in this List.

hashCode

This calculates a hash code for this collection. It is appropriate for use in a hash table.

hasIn

This is true if a collection's equivalent to a filesystem walk finds the value in question.

indexOf

The index of the first occurrence in this List, for example, Array.prototype.indexOf.

interpose

Interpose a separator between individual List entries.

interleave

Interleave the provided Lists into one list of the same type.

isEmpty

This tells whether this iterable has values or not.

isList

This is true if the value is a List.

isSubset

True if every value in the comparison iterable is in this List.

isSuperset

True if every value in this List is in the comparison iterable.

join

This joins together as a string with a separator (default).

keys

An iterator of this List's keys.

keySeq

Returns a KeySeq for this iterable, discarding all values.

last

The last value in the List.

lastIndexOf

Returns the last index at which a value can be found in this List.

List

The constructor for lists.

map

Returns a new List with values passed through a map function.

max

Returns the maximum value in this collection.

maxBy

This is like max, but with more fine-grained control.

merge

Merges iterables or JavaScript objects into one List.

mergeDeep

A recursive analog to merge.

mergeDeepIn

Performs a deep merge, starting at a given keypath.

mergeDeepWith

This is like mergeDeep, but uses a provided merger function when nodes conflict.

mergeIn

This is a combination of update and merge. It performs a merger at a specified keypath.

mergeWith

This is like merge, but uses a provided merger function when nodes conflict.

min

Returns the minimum value in the List.

minBy

Returns the minimum value in the List as determined by a helper function you provide.

of

Creates a new list containing its arguments as values.

pop

This returns everything in this List but the last. Note that this differs from the standard push semantics, but a regular push() can be simulated by calling last() before push().

push

Returns a new list with the specified value (or values) appended at the end.

reduce

Calls the reducing function for every value and returns the accumulated value.

reduceRight

This is similar to reduce, but starts at the right and moves progressively to the left, the opposite of the basic reduce.

rest

Returns the tail of a List, that is, all entries but the first.

reverse

Provides a List in reverse order.

set

Returns a new List with the value at the index.

setIn

Return a new List with this value at the keypath.

setSize

Creates a new List with the size that you specify, truncating or adding undefined values as needed.

shift

Creates a new list with the first value subtracted and all other values shifted down.

skip

Returns all that is left of the List when the first n entries are not included.

skipLast

Returns all that is left of the List when the last n entries are not included.

skipUntil

Returns a new iterable containing all entries after the first where a provided predicate is true.

skipWhile

This returns a new iterable containing all entries before a provided predicate is false.

slice

Returns a new iterable containing this list's contents from the start value to one before the last, inclusive.

some

True if a predicate returns true for any element of the List.

sort

Returns a new List sorted by an optional comparator.

sortBy

Returns a new List sorted by an optional comparator value mapper, with more detailed information available for the comparator and therefore more refined results.

splice

Replaces a segment of the first list with the second, or deletes it if no second list is provided.

take

Creates a new List containing exactly the first n entries in a List.

takeLast

Creates a new List containing exactly the last n entries in a List.

takeUntil

This returns a new List containing all entries as long as the predicate returns false; then it stops.

takeWhile

This returns a new List containing all entries as long as the predicate returns true; then it stops.

toArray

Shallowly converts this List to an Array, discarding the keys.

toIndexedSeq

Return an IndexedSeq of this List, discarding the keys.

toJS

Deeply converts this List into an Array. This method has toJSON() as an alias, although the documentation does not clearly state whether or not toJS() returns JavaScript objects, while toJSON() returns a JSON-encoded string.

toKeyedSeq

Returns a KeyedSeq from this List where indices are treated as keys.

toList

Returns itself.

toMap

Converts this List into a Map.

toObject

Shallowly converts this List into an Object.

toOrderedMap

Convert this List into a Map, preserving the order of iteration.

toSeq

Returns an IndexedSeq.

toSet

Converts this List to a Set, discarding the keys.

toSetSeq

Converts this List to a SetSeq, discarding the keys.

toStack

Convert this List to a Stack, discarding the keys.

unshift

Prepend the provided values to a List.

update

Update an entry on a List by a provided updater function.

updateIn

Update an entry, as in update(), but at a given key path.

values

An iterator of this List's values.

valueSeq

An IndexedSeq of this List's values.

withMutations

This is an optimization (recall "Premature optimization is the root of all evil," said by Donald Knuth) hook meant to allow more performant work when multiple mutations are performed. It is to be used when there are known and persistent performance issues where other tools have demonstrably not solved the problem.

zip

Returns an iterable zipped (that is, joined pairwise to make a list of 2-tuples) with this List.

zipWith

Returns an iterable zipped with a custom zipping function.

The documentation for the API, which is under the Documentation link available on the home page, is pretty clear. But as a rule, Immutable.js collections do what a functional programmer would expect them to do as much as possible, and indeed there appears to be a presumable overriding design consideration of "do what a functional programmer would want as much as we can."

Note

One thing that might be an unpleasant surprise to functional programmers is that the documentation does not explain how to create infinite lists. It is not obvious how one might create a generator for a list (if they do so at all), or produce lists of mathematical sequences, such as all counting all numbers, positive even numbers, squares, primes, Fibonacci numbers, powers of 2, factorials, and so on. Such functionality is apparently not supported (at the time of writing this book). Lazy sequences cannot build infinite lists with Immutable.js because constructing a collection includes an eager inclusion of all elements ever in the list, which must therefore be finite. It shouldn't be terribly difficult to create lazy, and potentially infinite, data structures in the style of Immutable.js that have a memoized generator inside and allow you to XYZ.take(5). But Immutable.js appears not to have expanded into that territory yet.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.63.62