immutable
- Version 5.0.3
- Published
- 687 kB
- No dependencies
- MIT license
Install
npm i immutable
yarn add immutable
pnpm add immutable
Overview
Immutable Data Collections
Index
Functions
- Collection()
- fromJS()
- get()
- getIn()
- has()
- hash()
- hasIn()
- is()
- isAssociative()
- isCollection()
- isImmutable()
- isIndexed()
- isKeyed()
- isList()
- isMap()
- isOrdered()
- isOrderedMap()
- isOrderedSet()
- isRecord()
- isSeq()
- isSet()
- isStack()
- isValueObject()
- List()
- Map()
- merge()
- mergeDeep()
- mergeDeepWith()
- mergeWith()
- OrderedMap()
- OrderedSet()
- Range()
- Record()
- remove()
- removeIn()
- Repeat()
- Seq()
- set()
- Set()
- setIn()
- Stack()
- update()
- updateIn()
Interfaces
Collection
- [Symbol.iterator]()
- butLast()
- concat()
- contains()
- count()
- countBy()
- entries()
- entrySeq()
- equals()
- every()
- filter()
- filterNot()
- find()
- findEntry()
- findKey()
- findLast()
- findLastEntry()
- findLastKey()
- first()
- flatMap()
- flatten()
- forEach()
- get()
- getIn()
- groupBy()
- has()
- hashCode()
- hasIn()
- includes()
- isEmpty()
- isSubset()
- isSuperset()
- join()
- keyOf()
- keys()
- keySeq()
- last()
- lastKeyOf()
- map()
- max()
- maxBy()
- min()
- minBy()
- partition()
- reduce()
- reduceRight()
- rest()
- reverse()
- skip()
- skipLast()
- skipUntil()
- skipWhile()
- slice()
- some()
- sort()
- sortBy()
- take()
- takeLast()
- takeUntil()
- takeWhile()
- toArray()
- toIndexedSeq()
- toJS()
- toJSON()
- toKeyedSeq()
- toList()
- toMap()
- toObject()
- toOrderedMap()
- toOrderedSet()
- toSeq()
- toSet()
- toSetSeq()
- toStack()
- update()
- values()
- valueSeq()
Enums
Type Aliases
Namespaces
Functions
function Collection
Collection: typeof Collection;
Creates a Collection.
The type of Collection created is based on the input.
* If an
Collection
, that sameCollection
. * If an Array-like, anCollection.Indexed
. * If an Object with an Iterator defined, anCollection.Indexed
. * If an Object, anCollection.Keyed
.This methods forces the conversion of Objects and Strings to Collections. If you want to ensure that a Collection of one item is returned, use
Seq.of
.Note: An Iterator itself will be treated as an object, becoming a
Seq.Keyed
, which is usually not what you want. You should turn your Iterator Object into an iterable object by defining a Symbol.iterator (or @@iterator) method which returnsthis
.Note:
Collection
is a conversion function and not a class, and does not use thenew
keyword during construction.
function fromJS
fromJS: { <JSValue>(jsValue: JSValue, reviver?: undefined): FromJS<JSValue>; ( jsValue: unknown, reviver?: ( key: string | number, sequence: | Collection.Indexed<unknown> | Collection.Keyed<string, unknown>, path?: (string | number)[] ) => unknown ): Collection<unknown, unknown>;};
Deeply converts plain JS objects and arrays to Immutable Maps and Lists.
fromJS
will convert Arrays and [array-like objects][2] to a List, and plain objects (without a custom prototype) to a Map. [Iterable objects][3] may be converted to List, Map, or Set.If a
reviver
is optionally provided, it will be called with every collection as a Seq (beginning with the most nested collections and proceeding to the top-level collection itself), along with the key referring to each collection and the parent JS object provided asthis
. For the top level, object, the key will be""
. Thisreviver
is expected to return a new Immutable Collection, allowing for custom conversions from deep JS objects. Finally, apath
is provided which is the sequence of keys to this value from the starting value.reviver
acts similarly to the [same parameter inJSON.parse
][1].If
reviver
is not provided, the default behavior will convert Objects into Maps and Arrays into Lists like so:<!-- runkit:activate -->
const { fromJS, isKeyed } = require('immutable')function (key, value) {return isKeyed(value) ? value.toMap() : value.toList()}Accordingly, this example converts native JS data to OrderedMap and List:
<!-- runkit:activate -->
const { fromJS, isKeyed } = require('immutable')fromJS({ a: {b: [10, 20, 30]}, c: 40}, function (key, value, path) {console.log(key, value, path)return isKeyed(value) ? value.toOrderedMap() : value.toList()})> "b", [ 10, 20, 30 ], [ "a", "b" ]> "a", {b: [10, 20, 30]}, [ "a" ]> "", {a: {b: [10, 20, 30]}, c: 40}, []Keep in mind, when using JS objects to construct Immutable Maps, that JavaScript Object properties are always strings, even if written in a quote-less shorthand, while Immutable Maps accept keys of any type.
<!-- runkit:activate -->
const { Map } = require('immutable')let obj = { 1: "one" };Object.keys(obj); // [ "1" ]assert.equal(obj["1"], obj[1]); // "one" === "one"let map = Map(obj);assert.notEqual(map.get("1"), map.get(1)); // "one" !== undefinedProperty access for JavaScript Objects first converts the key to a string, but since Immutable Map keys can be of any type the argument to
get()
is not altered.[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter "Using the reviver parameter" [2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects "Working with array-like objects" [3]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol "The iterable protocol"
function get
get: { <K, V>(collection: Collection<K, V>, key: K): V | undefined; <K, V, NSV>(collection: Collection<K, V>, key: K, notSetValue: NSV): V | NSV; <TProps extends object, K extends keyof TProps>( record: Record<TProps>, key: K, notSetValue: unknown ): TProps[K]; <V>(collection: V[], key: number): V; <V, NSV>(collection: V[], key: number, notSetValue: NSV): V | NSV; <C extends object, K extends keyof C>( object: C, key: K, notSetValue: unknown ): C[K]; <V>(collection: { [key: string]: V }, key: string): V; <V, NSV>(collection: { [key: string]: V }, key: string, notSetValue: NSV): | V | NSV;};
Returns the value within the provided collection associated with the provided key, or notSetValue if the key is not defined in the collection.
A functional alternative to
collection.get(key)
which will also work on plain Objects and Arrays as an alternative forcollection[key]
.<!-- runkit:activate -->
const { get } = require('immutable')get([ 'dog', 'frog', 'cat' ], 2) // 'frog'get({ x: 123, y: 456 }, 'x') // 123get({ x: 123, y: 456 }, 'z', 'ifNotSet') // 'ifNotSet'
function getIn
getIn: ( collection: unknown, keyPath: Iterable<unknown>, notSetValue?: unknown) => unknown;
Returns the value at the provided key path starting at the provided collection, or notSetValue if the key path is not defined.
A functional alternative to
collection.getIn(keypath)
which will also work with plain Objects and Arrays.<!-- runkit:activate -->
const { getIn } = require('immutable')getIn({ x: { y: { z: 123 }}}, ['x', 'y', 'z']) // 123getIn({ x: { y: { z: 123 }}}, ['x', 'q', 'p'], 'ifNotSet') // 'ifNotSet'
function has
has: (collection: object, key: unknown) => boolean;
Returns true if the key is defined in the provided collection.
A functional alternative to
collection.has(key)
which will also work with plain Objects and Arrays as an alternative forcollection.hasOwnProperty(key)
.<!-- runkit:activate -->
const { has } = require('immutable')has([ 'dog', 'frog', 'cat' ], 2) // truehas([ 'dog', 'frog', 'cat' ], 5) // falsehas({ x: 123, y: 456 }, 'x') // truehas({ x: 123, y: 456 }, 'z') // false
function hash
hash: (value: unknown) => number;
The
hash()
function is an important part of how Immutable determines if two values are equivalent and is used to determine how to store those values. Provided with any value,hash()
will return a 31-bit integer.When designing Objects which may be equal, it's important that when a
.equals()
method returns true, that both values.hashCode()
method return the same value.hash()
may be used to produce those values.For non-Immutable Objects that do not provide a
.hashCode()
functions (including plain Objects, plain Arrays, Date objects, etc), a unique hash value will be created for each *instance*. That is, the create hash represents referential equality, and not value equality for Objects. This ensures that if that Object is mutated over time that its hash code will remain consistent, allowing Objects to be used as keys and values in Immutable.js collections.Note that
hash()
attempts to balance between speed and avoiding collisions, however it makes no attempt to produce secure hashes.*New in Version 4.0*
function hasIn
hasIn: (collection: unknown, keyPath: Iterable<unknown>) => boolean;
Returns true if the key path is defined in the provided collection.
A functional alternative to
collection.hasIn(keypath)
which will also work with plain Objects and Arrays.<!-- runkit:activate -->
const { hasIn } = require('immutable')hasIn({ x: { y: { z: 123 }}}, ['x', 'y', 'z']) // truehasIn({ x: { y: { z: 123 }}}, ['x', 'q', 'p']) // false
function is
is: (first: unknown, second: unknown) => boolean;
Value equality check with semantics similar to
Object.is
, but treats ImmutableCollection
s as values, equal if the secondCollection
includes equivalent values.It's used throughout Immutable when checking for equality, including
Map
key equality andSet
membership.<!-- runkit:activate -->
const { Map, is } = require('immutable')const map1 = Map({ a: 1, b: 1, c: 1 })const map2 = Map({ a: 1, b: 1, c: 1 })assert.equal(map1 !== map2, true)assert.equal(Object.is(map1, map2), false)assert.equal(is(map1, map2), true)is()
compares primitive types like strings and numbers, Immutable.js collections likeMap
andList
, but also any custom object which implementsValueObject
by providingequals()
andhashCode()
methods.Note: Unlike
Object.is
,Immutable.is
assumes0
and-0
are the same value, matching the behavior of ES6 Map key equality.
function isAssociative
isAssociative: ( maybeAssociative: unknown) => maybeAssociative is | Collection.Indexed<unknown> | Collection.Keyed<unknown, unknown>;
True if
maybeAssociative
is either a Keyed or Indexed Collection.<!-- runkit:activate -->
const { isAssociative, Map, List, Stack, Set } = require('immutable');isAssociative([]); // falseisAssociative({}); // falseisAssociative(Map()); // trueisAssociative(List()); // trueisAssociative(Stack()); // trueisAssociative(Set()); // false
function isCollection
isCollection: ( maybeCollection: unknown) => maybeCollection is Collection<unknown, unknown>;
True if
maybeCollection
is a Collection, or any of its subclasses.<!-- runkit:activate -->
const { isCollection, Map, List, Stack } = require('immutable');isCollection([]); // falseisCollection({}); // falseisCollection(Map()); // trueisCollection(List()); // trueisCollection(Stack()); // true
function isImmutable
isImmutable: ( maybeImmutable: unknown) => maybeImmutable is Collection<unknown, unknown>;
True if
maybeImmutable
is an Immutable Collection or Record.Note: Still returns true even if the collections is within a
withMutations()
.<!-- runkit:activate -->
const { isImmutable, Map, List, Stack } = require('immutable');isImmutable([]); // falseisImmutable({}); // falseisImmutable(Map()); // trueisImmutable(List()); // trueisImmutable(Stack()); // trueisImmutable(Map().asMutable()); // true
function isIndexed
isIndexed: ( maybeIndexed: unknown) => maybeIndexed is Collection.Indexed<unknown>;
True if
maybeIndexed
is a Collection.Indexed, or any of its subclasses.<!-- runkit:activate -->
const { isIndexed, Map, List, Stack, Set } = require('immutable');isIndexed([]); // falseisIndexed({}); // falseisIndexed(Map()); // falseisIndexed(List()); // trueisIndexed(Stack()); // trueisIndexed(Set()); // false
function isKeyed
isKeyed: ( maybeKeyed: unknown) => maybeKeyed is Collection.Keyed<unknown, unknown>;
True if
maybeKeyed
is a Collection.Keyed, or any of its subclasses.<!-- runkit:activate -->
const { isKeyed, Map, List, Stack } = require('immutable');isKeyed([]); // falseisKeyed({}); // falseisKeyed(Map()); // trueisKeyed(List()); // falseisKeyed(Stack()); // false
function isList
isList: (maybeList: unknown) => maybeList is List<unknown>;
True if
maybeList
is a List.
function isMap
isMap: (maybeMap: unknown) => maybeMap is Map<unknown, unknown>;
True if
maybeMap
is a Map.Also true for OrderedMaps.
function isOrdered
isOrdered: (maybeOrdered: unknown) => boolean;
True if
maybeOrdered
is a Collection where iteration order is well defined. True for Collection.Indexed as well as OrderedMap and OrderedSet.<!-- runkit:activate -->
const { isOrdered, Map, OrderedMap, List, Set } = require('immutable');isOrdered([]); // falseisOrdered({}); // falseisOrdered(Map()); // falseisOrdered(OrderedMap()); // trueisOrdered(List()); // trueisOrdered(Set()); // false
function isOrderedMap
isOrderedMap: ( maybeOrderedMap: unknown) => maybeOrderedMap is OrderedMap<unknown, unknown>;
True if
maybeOrderedMap
is an OrderedMap.
function isOrderedSet
isOrderedSet: ( maybeOrderedSet: unknown) => maybeOrderedSet is OrderedSet<unknown>;
True if
maybeOrderedSet
is an OrderedSet.
function isRecord
isRecord: (maybeRecord: unknown) => maybeRecord is Record<{}>;
True if
maybeRecord
is a Record.
function isSeq
isSeq: ( maybeSeq: unknown) => maybeSeq is | Seq.Indexed<unknown> | Seq.Keyed<unknown, unknown> | Seq.Set<unknown>;
True if
maybeSeq
is a Seq.
function isSet
isSet: (maybeSet: unknown) => maybeSet is Set<unknown>;
True if
maybeSet
is a Set.Also true for OrderedSets.
function isStack
isStack: (maybeStack: unknown) => maybeStack is Stack<unknown>;
True if
maybeStack
is a Stack.
function isValueObject
isValueObject: (maybeValue: unknown) => maybeValue is ValueObject;
True if
maybeValue
is a JavaScript Object which has *both*equals()
andhashCode()
methods.Any two instances of *value objects* can be compared for value equality with
Immutable.is()
and can be used as keys in aMap
or members in aSet
.
function List
List: typeof List;
Create a new immutable List containing the values of the provided collection-like.
Note:
List
is a factory function and not a class, and does not use thenew
keyword during construction.<!-- runkit:activate -->
const { List, Set } = require('immutable')const emptyList = List()// List []const plainArray = [ 1, 2, 3, 4 ]const listFromPlainArray = List(plainArray)// List [ 1, 2, 3, 4 ]const plainSet = Set([ 1, 2, 3, 4 ])const listFromPlainSet = List(plainSet)// List [ 1, 2, 3, 4 ]const arrayIterator = plainArray[Symbol.iterator]()const listFromCollectionArray = List(arrayIterator)// List [ 1, 2, 3, 4 ]listFromPlainArray.equals(listFromCollectionArray) // truelistFromPlainSet.equals(listFromCollectionArray) // truelistFromPlainSet.equals(listFromPlainArray) // true
function Map
Map: typeof Map;
Creates a new Immutable Map.
Created with the same key value pairs as the provided Collection.Keyed or JavaScript Object or expects a Collection of [K, V] tuple entries.
Note:
Map
is a factory function and not a class, and does not use thenew
keyword during construction.<!-- runkit:activate -->
const { Map } = require('immutable')Map({ key: "value" })Map([ [ "key", "value" ] ])Keep in mind, when using JS objects to construct Immutable Maps, that JavaScript Object properties are always strings, even if written in a quote-less shorthand, while Immutable Maps accept keys of any type.
<!-- runkit:activate { "preamble": "const { Map } = require('immutable');" } -->
let obj = { 1: "one" }Object.keys(obj) // [ "1" ]assert.equal(obj["1"], obj[1]) // "one" === "one"let map = Map(obj)assert.notEqual(map.get("1"), map.get(1)) // "one" !== undefinedProperty access for JavaScript Objects first converts the key to a string, but since Immutable Map keys can be of any type the argument to
get()
is not altered.
function merge
merge: <C>( collection: C, ...collections: ( | Iterable<unknown> | Iterable<[unknown, unknown]> | { [key: string]: unknown } )[]) => C;
Returns a copy of the collection with the remaining collections merged in.
A functional alternative to
collection.merge()
which will also work with plain Objects and Arrays.<!-- runkit:activate -->
const { merge } = require('immutable')const original = { x: 123, y: 456 }merge(original, { y: 789, z: 'abc' }) // { x: 123, y: 789, z: 'abc' }console.log(original) // { x: 123, y: 456 }
function mergeDeep
mergeDeep: <C>( collection: C, ...collections: ( | Iterable<unknown> | Iterable<[unknown, unknown]> | { [key: string]: unknown } )[]) => C;
Like
merge()
, but when two compatible collections are encountered with the same key, it merges them as well, recursing deeply through the nested data. Two collections are considered to be compatible (and thus will be merged together) if they both fall into one of three categories: keyed (e.g.,Map
s,Record
s, and objects), indexed (e.g.,List
s and arrays), or set-like (e.g.,Set
s). If they fall into separate categories,mergeDeep
will replace the existing collection with the collection being merged in. This behavior can be customized by usingmergeDeepWith()
.Note: Indexed and set-like collections are merged using
concat()
/union()
and therefore do not recurse.A functional alternative to
collection.mergeDeep()
which will also work with plain Objects and Arrays.<!-- runkit:activate -->
const { mergeDeep } = require('immutable')const original = { x: { y: 123 }}mergeDeep(original, { x: { z: 456 }}) // { x: { y: 123, z: 456 }}console.log(original) // { x: { y: 123 }}
function mergeDeepWith
mergeDeepWith: <C>( merger: (oldVal: unknown, newVal: unknown, key: unknown) => unknown, collection: C, ...collections: ( | Iterable<unknown> | Iterable<[unknown, unknown]> | { [key: string]: unknown } )[]) => C;
Like
mergeDeep()
, but when two non-collections or incompatible collections are encountered at the same key, it uses themerger
function to determine the resulting value. Collections are considered incompatible if they fall into separate categories between keyed, indexed, and set-like.A functional alternative to
collection.mergeDeepWith()
which will also work with plain Objects and Arrays.<!-- runkit:activate -->
const { mergeDeepWith } = require('immutable')const original = { x: { y: 123 }}mergeDeepWith((oldVal, newVal) => oldVal + newVal,original,{ x: { y: 456 }}) // { x: { y: 579 }}console.log(original) // { x: { y: 123 }}
function mergeWith
mergeWith: <C>( merger: (oldVal: unknown, newVal: unknown, key: unknown) => unknown, collection: C, ...collections: ( | Iterable<unknown> | Iterable<[unknown, unknown]> | { [key: string]: unknown } )[]) => C;
Returns a copy of the collection with the remaining collections merged in, calling the
merger
function whenever an existing value is encountered.A functional alternative to
collection.mergeWith()
which will also work with plain Objects and Arrays.<!-- runkit:activate -->
const { mergeWith } = require('immutable')const original = { x: 123, y: 456 }mergeWith((oldVal, newVal) => oldVal + newVal,original,{ y: 789, z: 'abc' }) // { x: 123, y: 1245, z: 'abc' }console.log(original) // { x: 123, y: 456 }
function OrderedMap
OrderedMap: typeof OrderedMap;
Creates a new Immutable OrderedMap.
Created with the same key value pairs as the provided Collection.Keyed or JavaScript Object or expects a Collection of [K, V] tuple entries.
The iteration order of key-value pairs provided to this constructor will be preserved in the OrderedMap.
let newOrderedMap = OrderedMap({key: "value"}) let newOrderedMap = OrderedMap([["key", "value"]])
Note:
OrderedMap
is a factory function and not a class, and does not use thenew
keyword during construction.
function OrderedSet
OrderedSet: typeof OrderedSet;
Create a new immutable OrderedSet containing the values of the provided collection-like.
Note:
OrderedSet
is a factory function and not a class, and does not use thenew
keyword during construction.
function Range
Range: (start: number, end: number, step?: number) => Seq.Indexed<number>;
Returns a Seq.Indexed of numbers from
start
(inclusive) toend
(exclusive), bystep
, wherestart
defaults to 0,step
to 1, andend
to infinity. Whenstart
is equal toend
, returns empty range.Note:
Range
is a factory function and not a class, and does not use thenew
keyword during construction.const { Range } = require('immutable')Range() // [ 0, 1, 2, 3, ... ]Range(10) // [ 10, 11, 12, 13, ... ]Range(10, 15) // [ 10, 11, 12, 13, 14 ]Range(10, 30, 5) // [ 10, 15, 20, 25 ]Range(30, 10, 5) // [ 30, 25, 20, 15 ]Range(30, 30, 5) // []
function Record
Record: typeof Record;
Unlike other types in Immutable.js, the
Record()
function creates a new Record Factory, which is a function that creates Record instances.See above for examples of using
Record()
.Note:
Record
is a factory function and not a class, and does not use thenew
keyword during construction.
function remove
remove: { <K, C extends Collection<K, unknown>>(collection: C, key: K): C; <TProps extends object, C extends Record<TProps>, K extends keyof TProps>( collection: C, key: K ): C; <C extends unknown[]>(collection: C, key: number): C; <C, K extends keyof C>(collection: C, key: K): C; <C extends { [key: string]: unknown }, K extends keyof C>( collection: C, key: K ): C;};
Returns a copy of the collection with the value at key removed.
A functional alternative to
collection.remove(key)
which will also work with plain Objects and Arrays as an alternative fordelete collectionCopy[key]
.<!-- runkit:activate -->
const { remove } = require('immutable')const originalArray = [ 'dog', 'frog', 'cat' ]remove(originalArray, 1) // [ 'dog', 'cat' ]console.log(originalArray) // [ 'dog', 'frog', 'cat' ]const originalObject = { x: 123, y: 456 }remove(originalObject, 'x') // { y: 456 }console.log(originalObject) // { x: 123, y: 456 }
function removeIn
removeIn: <C>(collection: C, keyPath: Iterable<unknown>) => C;
Returns a copy of the collection with the value at the key path removed.
A functional alternative to
collection.removeIn(keypath)
which will also work with plain Objects and Arrays.<!-- runkit:activate -->
const { removeIn } = require('immutable')const original = { x: { y: { z: 123 }}}removeIn(original, ['x', 'y', 'z']) // { x: { y: {}}}console.log(original) // { x: { y: { z: 123 }}}
function Repeat
Repeat: <T>(value: T, times?: number) => Seq.Indexed<T>;
Returns a Seq.Indexed of
value
repeatedtimes
times. Whentimes
is not defined, returns an infiniteSeq
ofvalue
.Note:
Repeat
is a factory function and not a class, and does not use thenew
keyword during construction.const { Repeat } = require('immutable')Repeat('foo') // [ 'foo', 'foo', 'foo', ... ]Repeat('bar', 4) // [ 'bar', 'bar', 'bar', 'bar' ]
function Seq
Seq: typeof Seq;
Creates a Seq.
Returns a particular kind of
Seq
based on the input.* If a
Seq
, that sameSeq
. * If anCollection
, aSeq
of the same kind (Keyed, Indexed, or Set). * If an Array-like, anSeq.Indexed
. * If an Iterable Object, anSeq.Indexed
. * If an Object, aSeq.Keyed
.Note: An Iterator itself will be treated as an object, becoming a
Seq.Keyed
, which is usually not what you want. You should turn your Iterator Object into an iterable object by defining a Symbol.iterator (or @@iterator) method which returnsthis
.Note:
Seq
is a conversion function and not a class, and does not use thenew
keyword during construction.
function set
set: { <K, V, C extends Collection<K, V>>(collection: C, key: K, value: V): C; <TProps extends object, C extends Record<TProps>, K extends keyof TProps>( record: C, key: K, value: TProps[K] ): C; <V, C extends V[]>(collection: C, key: number, value: V): C; <C, K extends keyof C>(object: C, key: K, value: C[K]): C; <V, C extends { [key: string]: V }>(collection: C, key: string, value: V): C;};
Returns a copy of the collection with the value at key set to the provided value.
A functional alternative to
collection.set(key, value)
which will also work with plain Objects and Arrays as an alternative forcollectionCopy[key] = value
.<!-- runkit:activate -->
const { set } = require('immutable')const originalArray = [ 'dog', 'frog', 'cat' ]set(originalArray, 1, 'cow') // [ 'dog', 'cow', 'cat' ]console.log(originalArray) // [ 'dog', 'frog', 'cat' ]const originalObject = { x: 123, y: 456 }set(originalObject, 'x', 789) // { x: 789, y: 456 }console.log(originalObject) // { x: 123, y: 456 }
function Set
Set: typeof Set;
Create a new immutable Set containing the values of the provided collection-like.
Note:
Set
is a factory function and not a class, and does not use thenew
keyword during construction.
function setIn
setIn: <C>(collection: C, keyPath: Iterable<unknown>, value: unknown) => C;
Returns a copy of the collection with the value at the key path set to the provided value.
A functional alternative to
collection.setIn(keypath)
which will also work with plain Objects and Arrays.<!-- runkit:activate -->
const { setIn } = require('immutable')const original = { x: { y: { z: 123 }}}setIn(original, ['x', 'y', 'z'], 456) // { x: { y: { z: 456 }}}console.log(original) // { x: { y: { z: 123 }}}
function Stack
Stack: typeof Stack;
Create a new immutable Stack containing the values of the provided collection-like.
The iteration order of the provided collection is preserved in the resulting
Stack
.Note:
Stack
is a factory function and not a class, and does not use thenew
keyword during construction.
function update
update: { <K, V, C extends Collection<K, V>>( collection: C, key: K, updater: (value: V | undefined) => V | undefined ): C; <K, V, C extends Collection<K, V>, NSV>( collection: C, key: K, notSetValue: NSV, updater: (value: V | NSV) => V ): C; <TProps extends object, C extends Record<TProps>, K extends keyof TProps>( record: C, key: K, updater: (value: TProps[K]) => TProps[K] ): C; <TProps extends object, C extends Record<TProps>, K extends keyof TProps, NSV>( record: C, key: K, notSetValue: NSV, updater: (value: NSV | TProps[K]) => TProps[K] ): C; <V>(collection: V[], key: number, updater: (value: V) => V): V[]; <V, NSV>( collection: V[], key: number, notSetValue: NSV, updater: (value: V | NSV) => V ): V[]; <C, K extends keyof C>(object: C, key: K, updater: (value: C[K]) => C[K]): C; <C, K extends keyof C, NSV>( object: C, key: K, notSetValue: NSV, updater: (value: NSV | C[K]) => C[K] ): C; <V, C extends { [key: string]: V }, K extends keyof C>( collection: C, key: K, updater: (value: V) => V ): { [key: string]: V }; <V, C extends { [key: string]: V }, K extends keyof C, NSV>( collection: C, key: K, notSetValue: NSV, updater: (value: V | NSV) => V ): { [key: string]: V };};
Returns a copy of the collection with the value at key set to the result of providing the existing value to the updating function.
A functional alternative to
collection.update(key, fn)
which will also work with plain Objects and Arrays as an alternative forcollectionCopy[key] = fn(collection[key])
.<!-- runkit:activate -->
const { update } = require('immutable')const originalArray = [ 'dog', 'frog', 'cat' ]update(originalArray, 1, val => val.toUpperCase()) // [ 'dog', 'FROG', 'cat' ]console.log(originalArray) // [ 'dog', 'frog', 'cat' ]const originalObject = { x: 123, y: 456 }update(originalObject, 'x', val => val * 6) // { x: 738, y: 456 }console.log(originalObject) // { x: 123, y: 456 }
function updateIn
updateIn: { <C>( collection: C, keyPath: Iterable<unknown>, updater: (value: unknown) => unknown ): C; <C>( collection: C, keyPath: Iterable<unknown>, notSetValue: unknown, updater: (value: unknown) => unknown ): C;};
Returns a copy of the collection with the value at key path set to the result of providing the existing value to the updating function.
A functional alternative to
collection.updateIn(keypath)
which will also work with plain Objects and Arrays.<!-- runkit:activate -->
const { updateIn } = require('immutable')const original = { x: { y: { z: 123 }}}updateIn(original, ['x', 'y', 'z'], val => val * 6) // { x: { y: { z: 738 }}}console.log(original) // { x: { y: { z: 123 }}}
Interfaces
interface Collection
interface Collection<K, V> extends ValueObject {}
method [Symbol.iterator]
[Symbol.iterator]: () => IterableIterator<unknown>;
method butLast
butLast: () => this;
Returns a new Collection of the same type containing all entries except the last.
method concat
concat: (...valuesOrCollections: Array<unknown>) => Collection<unknown, unknown>;
Returns a new Collection of the same type with other values and collection-like concatenated to this one.
For Seqs, all entries will be present in the resulting Seq, even if they have the same key.
method contains
contains: (value: V) => boolean;
method count
count: { (): number; ( predicate: (value: V, key: K, iter: this) => boolean, context?: unknown ): number;};
Returns the size of this Collection.
Regardless of if this Collection can describe its size lazily (some Seqs cannot), this method will always return the correct size. E.g. it evaluates a lazy
Seq
if necessary.If
predicate
is provided, then this returns the count of entries in the Collection for which thepredicate
returns true.
method countBy
countBy: <G>( grouper: (value: V, key: K, iter: this) => G, context?: unknown) => Map<G, number>;
Returns a
Seq.Keyed
of counts, grouped by the return value of thegrouper
function.Note: This is not a lazy operation.
method entries
entries: () => IterableIterator<[K, V]>;
An iterator of this
Collection
's entries as[ key, value ]
tuples.Note: this will return an ES6 iterator which does not support Immutable.js sequence algorithms. Use
entrySeq
instead, if this is what you want.
method entrySeq
entrySeq: () => Seq.Indexed<[K, V]>;
Returns a new Seq.Indexed of [key, value] tuples.
method equals
equals: (other: unknown) => boolean;
True if this and the other Collection have value equality, as defined by
Immutable.is()
.Note: This is equivalent to
Immutable.is(this, other)
, but provided to allow for chained expressions.
method every
every: ( predicate: (value: V, key: K, iter: this) => boolean, context?: unknown) => boolean;
True if
predicate
returns true for all entries in the Collection.
method filter
filter: { <F extends V>( predicate: (value: V, key: K, iter: this) => value is F, context?: unknown ): Collection<K, F>; ( predicate: (value: V, key: K, iter: this) => unknown, context?: unknown ): this;};
Returns a new Collection of the same type with only the entries for which the
predicate
function returns true.<!-- runkit:activate -->
const { Map } = require('immutable')Map({ a: 1, b: 2, c: 3, d: 4}).filter(x => x % 2 === 0)// Map { "b": 2, "d": 4 }Note:
filter()
always returns a new instance, even if it results in not filtering out any values.
method filterNot
filterNot: ( predicate: (value: V, key: K, iter: this) => boolean, context?: unknown) => this;
Returns a new Collection of the same type with only the entries for which the
predicate
function returns false.<!-- runkit:activate -->
const { Map } = require('immutable')Map({ a: 1, b: 2, c: 3, d: 4}).filterNot(x => x % 2 === 0)// Map { "a": 1, "c": 3 }Note:
filterNot()
always returns a new instance, even if it results in not filtering out any values.
method find
find: ( predicate: (value: V, key: K, iter: this) => boolean, context?: unknown, notSetValue?: V) => V | undefined;
Returns the first value for which the
predicate
returns true.
method findEntry
findEntry: ( predicate: (value: V, key: K, iter: this) => boolean, context?: unknown, notSetValue?: V) => [K, V] | undefined;
Returns the first [key, value] entry for which the
predicate
returns true.
method findKey
findKey: ( predicate: (value: V, key: K, iter: this) => boolean, context?: unknown) => K | undefined;
Returns the key for which the
predicate
returns true.
method findLast
findLast: ( predicate: (value: V, key: K, iter: this) => boolean, context?: unknown, notSetValue?: V) => V | undefined;
Returns the last value for which the
predicate
returns true.Note:
predicate
will be called for each entry in reverse.
method findLastEntry
findLastEntry: ( predicate: (value: V, key: K, iter: this) => boolean, context?: unknown, notSetValue?: V) => [K, V] | undefined;
Returns the last [key, value] entry for which the
predicate
returns true.Note:
predicate
will be called for each entry in reverse.
method findLastKey
findLastKey: ( predicate: (value: V, key: K, iter: this) => boolean, context?: unknown) => K | undefined;
Returns the last key for which the
predicate
returns true.Note:
predicate
will be called for each entry in reverse.
method first
first: { <NSV>(notSetValue: NSV): V | NSV; (): V };
In case the
Collection
is not empty returns the first element of theCollection
. In case theCollection
is empty returns the optional default value if provided, if no default value is provided returns undefined.
method flatMap
flatMap: { <M>( mapper: (value: V, key: K, iter: this) => Iterable<M>, context?: unknown ): Collection<K, M>; <KM, VM>( mapper: (value: V, key: K, iter: this) => Iterable<[KM, VM]>, context?: unknown ): Collection<KM, VM>;};
Flat-maps the Collection, returning a Collection of the same type.
Similar to
collection.map(...).flatten(true)
.Flat-maps the Collection, returning a Collection of the same type.
Similar to
collection.map(...).flatten(true)
. Used for Dictionaries only.
method flatten
flatten: { (depth?: number): Collection<unknown, unknown>; (shallow?: boolean): Collection<unknown, unknown>;};
Flattens nested Collections.
Will deeply flatten the Collection by default, returning a Collection of the same type, but a
depth
can be provided in the form of a number or boolean (where true means to shallowly flatten one level). A depth of 0 (or shallow: false) will deeply flatten.Flattens only others Collection, not Arrays or Objects.
Note:
flatten(true)
operates on Collection<unknown, Collection<K, V>> and returns Collection<K, V>
method forEach
forEach: ( sideEffect: (value: V, key: K, iter: this) => unknown, context?: unknown) => number;
The
sideEffect
is executed for every entry in the Collection.Unlike
Array#forEach
, if any call ofsideEffect
returnsfalse
, the iteration will stop. Returns the number of entries iterated (including the last iteration which returned false).
method get
get: { <NSV>(key: K, notSetValue: NSV): V | NSV; (key: K): V };
Returns the value associated with the provided key, or notSetValue if the Collection does not contain this key.
Note: it is possible a key may be associated with an
undefined
value, so ifnotSetValue
is not provided and this method returnsundefined
, that does not guarantee the key was not found.
method getIn
getIn: (searchKeyPath: Iterable<unknown>, notSetValue?: unknown) => unknown;
Returns the value found by following a path of keys or indices through nested Collections.
<!-- runkit:activate -->
const { Map, List } = require('immutable')const deepData = Map({ x: List([ Map({ y: 123 }) ]) });deepData.getIn(['x', 0, 'y']) // 123Plain JavaScript Object or Arrays may be nested within an Immutable.js Collection, and getIn() can access those values as well:
<!-- runkit:activate -->
const { Map, List } = require('immutable')const deepData = Map({ x: [ { y: 123 } ] });deepData.getIn(['x', 0, 'y']) // 123
method groupBy
groupBy: <G>( grouper: (value: V, key: K, iter: this) => G, context?: unknown) => Map<G, this>;
Returns a
Map
ofCollection
, grouped by the return value of thegrouper
function.Note: This is always an eager operation.
<!-- runkit:activate -->
const { List, Map } = require('immutable')const listOfMaps = List([Map({ v: 0 }),Map({ v: 1 }),Map({ v: 1 }),Map({ v: 0 }),Map({ v: 2 })])const groupsOfMaps = listOfMaps.groupBy(x => x.get('v'))// Map {// 0: List [ Map{ "v": 0 }, Map { "v": 0 } ],// 1: List [ Map{ "v": 1 }, Map { "v": 1 } ],// 2: List [ Map{ "v": 2 } ],// }
method has
has: (key: K) => boolean;
True if a key exists within this
Collection
, usingImmutable.is
to determine equality
method hashCode
hashCode: () => number;
Computes and returns the hashed identity for this Collection.
The
hashCode
of a Collection is used to determine potential equality, and is used when adding this to aSet
or as a key in aMap
, enabling lookup via a different instance.<!-- runkit:activate { "preamble": "const { Set, List } = require('immutable')" } -->
const a = List([ 1, 2, 3 ]);const b = List([ 1, 2, 3 ]);assert.notStrictEqual(a, b); // different instancesconst set = Set([ a ]);assert.equal(set.has(b), true);If two values have the same
hashCode
, they are [not guaranteed to be equal][Hash Collision]. If two values have differenthashCode
s, they must not be equal.[Hash Collision]: https://en.wikipedia.org/wiki/Collision_(computer_science)
method hasIn
hasIn: (searchKeyPath: Iterable<unknown>) => boolean;
True if the result of following a path of keys or indices through nested Collections results in a set value.
method includes
includes: (value: V) => boolean;
True if a value exists within this
Collection
, usingImmutable.is
to determine equality contains
method isEmpty
isEmpty: () => boolean;
Returns true if this Collection includes no values.
For some lazy
Seq
,isEmpty
might need to iterate to determine emptiness. At most one iteration will occur.
method isSubset
isSubset: (iter: Iterable<V>) => boolean;
True if
iter
includes every value in this Collection.
method isSuperset
isSuperset: (iter: Iterable<V>) => boolean;
True if this Collection includes every value in
iter
.
method join
join: (separator?: string) => string;
Joins values together as a string, inserting a separator between each. The default separator is
","
.
method keyOf
keyOf: (searchValue: V) => K | undefined;
Returns the key associated with the search value, or undefined.
method keys
keys: () => IterableIterator<K>;
An iterator of this
Collection
's keys.Note: this will return an ES6 iterator which does not support Immutable.js sequence algorithms. Use
keySeq
instead, if this is what you want.
method keySeq
keySeq: () => Seq.Indexed<K>;
Returns a new Seq.Indexed of the keys of this Collection, discarding values.
method last
last: { <NSV>(notSetValue: NSV): V | NSV; (): V };
In case the
Collection
is not empty returns the last element of theCollection
. In case theCollection
is empty returns the optional default value if provided, if no default value is provided returns undefined.
method lastKeyOf
lastKeyOf: (searchValue: V) => K | undefined;
Returns the last key associated with the search value, or undefined.
method map
map: { <M>( mapper: (value: V, key: K, iter: this) => M, context?: unknown ): Collection<K, M>; (...args: never[]): unknown;};
Returns a new Collection of the same type with values passed through a
mapper
function.<!-- runkit:activate -->
const { Collection } = require('immutable')Collection({ a: 1, b: 2 }).map(x => 10 * x)// Seq { "a": 10, "b": 20 }Note:
map()
always returns a new instance, even if it produced the same value at every step.Note: used only for sets, which return Collection<M, M> but are otherwise identical to normal
map()
.
method max
max: (comparator?: Comparator<V>) => V | undefined;
Returns the maximum value in this collection. If any values are comparatively equivalent, the first one found will be returned.
The
comparator
is used in the same way asCollection#sort
. If it is not provided, the default comparator is>
.When two values are considered equivalent, the first encountered will be returned. Otherwise,
max
will operate independent of the order of input as long as the comparator is commutative. The default comparator>
is commutative *only* when types do not differ.If
comparator
returns 0 and either value is NaN, undefined, or null, that value will be returned.
method maxBy
maxBy: <C>( comparatorValueMapper: (value: V, key: K, iter: this) => C, comparator?: Comparator<C>) => V | undefined;
Like
max
, but also accepts acomparatorValueMapper
which allows for comparing by more sophisticated means:<!-- runkit:activate -->
const { List, } = require('immutable');const l = List([{ name: 'Bob', avgHit: 1 },{ name: 'Max', avgHit: 3 },{ name: 'Lili', avgHit: 2 } ,]);l.maxBy(i => i.avgHit); // will output { name: 'Max', avgHit: 3 }
method min
min: (comparator?: Comparator<V>) => V | undefined;
Returns the minimum value in this collection. If any values are comparatively equivalent, the first one found will be returned.
The
comparator
is used in the same way asCollection#sort
. If it is not provided, the default comparator is<
.When two values are considered equivalent, the first encountered will be returned. Otherwise,
min
will operate independent of the order of input as long as the comparator is commutative. The default comparator<
is commutative *only* when types do not differ.If
comparator
returns 0 and either value is NaN, undefined, or null, that value will be returned.
method minBy
minBy: <C>( comparatorValueMapper: (value: V, key: K, iter: this) => C, comparator?: Comparator<C>) => V | undefined;
Like
min
, but also accepts acomparatorValueMapper
which allows for comparing by more sophisticated means:<!-- runkit:activate -->
const { List, } = require('immutable');const l = List([{ name: 'Bob', avgHit: 1 },{ name: 'Max', avgHit: 3 },{ name: 'Lili', avgHit: 2 } ,]);l.minBy(i => i.avgHit); // will output { name: 'Bob', avgHit: 1 }
method partition
partition: { <F extends V, C>( predicate: (this: C, value: V, key: K, iter: this) => value is F, context?: C ): [Collection<K, V>, Collection<K, F>]; <C>( predicate: (this: C, value: V, key: K, iter: this) => unknown, context?: C ): [this, this];};
Returns a new Collection with the values for which the
predicate
function returns false and another for which is returns true.
method reduce
reduce: { <R>( reducer: (reduction: R, value: V, key: K, iter: this) => R, initialReduction: R, context?: unknown ): R; <R>(reducer: (reduction: V | R, value: V, key: K, iter: this) => R): R;};
Reduces the Collection to a value by calling the
reducer
for every entry in the Collection and passing along the reduced value.If
initialReduction
is not provided, the first item in the Collection will be used.See Also
Array#reduce
.
method reduceRight
reduceRight: { <R>( reducer: (reduction: R, value: V, key: K, iter: this) => R, initialReduction: R, context?: unknown ): R; <R>(reducer: (reduction: V | R, value: V, key: K, iter: this) => R): R;};
Reduces the Collection in reverse (from the right side).
Note: Similar to this.reverse().reduce(), and provided for parity with
Array#reduceRight
.
method rest
rest: () => this;
Returns a new Collection of the same type containing all entries except the first.
method reverse
reverse: () => this;
Returns a new Collection of the same type in reverse order.
method skip
skip: (amount: number) => this;
Returns a new Collection of the same type which excludes the first
amount
entries from this Collection.
method skipLast
skipLast: (amount: number) => this;
Returns a new Collection of the same type which excludes the last
amount
entries from this Collection.
method skipUntil
skipUntil: ( predicate: (value: V, key: K, iter: this) => boolean, context?: unknown) => this;
Returns a new Collection of the same type which includes entries starting from when
predicate
first returns true.<!-- runkit:activate -->
const { List } = require('immutable')List([ 'dog', 'frog', 'cat', 'hat', 'god' ]).skipUntil(x => x.match(/hat/))// List [ "hat", "god" ]
method skipWhile
skipWhile: ( predicate: (value: V, key: K, iter: this) => boolean, context?: unknown) => this;
Returns a new Collection of the same type which includes entries starting from when
predicate
first returns false.<!-- runkit:activate -->
const { List } = require('immutable')List([ 'dog', 'frog', 'cat', 'hat', 'god' ]).skipWhile(x => x.match(/g/))// List [ "cat", "hat", "god" ]
method slice
slice: (begin?: number, end?: number) => this;
Returns a new Collection of the same type representing a portion of this Collection from start up to but not including end.
If begin is negative, it is offset from the end of the Collection. e.g.
slice(-2)
returns a Collection of the last two entries. If it is not provided the new Collection will begin at the beginning of this Collection.If end is negative, it is offset from the end of the Collection. e.g.
slice(0, -1)
returns a Collection of everything but the last entry. If it is not provided, the new Collection will continue through the end of this Collection.If the requested slice is equivalent to the current Collection, then it will return itself.
method some
some: ( predicate: (value: V, key: K, iter: this) => boolean, context?: unknown) => boolean;
True if
predicate
returns true for any entry in the Collection.
method sort
sort: (comparator?: Comparator<V>) => this;
Returns a new Collection of the same type which includes the same entries, stably sorted by using a
comparator
.If a
comparator
is not provided, a default comparator uses<
and>
.comparator(valueA, valueB)
:* Returns
0
if the elements should not be swapped. * Returns-1
(or any negative number) ifvalueA
comes beforevalueB
* Returns1
(or any positive number) ifvalueA
comes aftervalueB
* Alternatively, can return a value of thePairSorting
enum type * Is pure, i.e. it must always return the same value for the same pair of values.When sorting collections which have no defined order, their ordered equivalents will be returned. e.g.
map.sort()
returns OrderedMap.<!-- runkit:activate -->
const { Map } = require('immutable')Map({ "c": 3, "a": 1, "b": 2 }).sort((a, b) => {if (a < b) { return -1; }if (a > b) { return 1; }if (a === b) { return 0; }});// OrderedMap { "a": 1, "b": 2, "c": 3 }Note:
sort()
Always returns a new instance, even if the original was already sorted.Note: This is always an eager operation.
method sortBy
sortBy: <C>( comparatorValueMapper: (value: V, key: K, iter: this) => C, comparator?: Comparator<C>) => this;
Like
sort
, but also accepts acomparatorValueMapper
which allows for sorting by more sophisticated means:<!-- runkit:activate -->
const { Map } = require('immutable')const beattles = Map({John: { name: "Lennon" },Paul: { name: "McCartney" },George: { name: "Harrison" },Ringo: { name: "Starr" },});beattles.sortBy(member => member.name);Note:
sortBy()
Always returns a new instance, even if the original was already sorted.Note: This is always an eager operation.
method take
take: (amount: number) => this;
Returns a new Collection of the same type which includes the first
amount
entries from this Collection.
method takeLast
takeLast: (amount: number) => this;
Returns a new Collection of the same type which includes the last
amount
entries from this Collection.
method takeUntil
takeUntil: ( predicate: (value: V, key: K, iter: this) => boolean, context?: unknown) => this;
Returns a new Collection of the same type which includes entries from this Collection as long as the
predicate
returns false.<!-- runkit:activate -->
const { List } = require('immutable')List([ 'dog', 'frog', 'cat', 'hat', 'god' ]).takeUntil(x => x.match(/at/))// List [ "dog", "frog" ]
method takeWhile
takeWhile: ( predicate: (value: V, key: K, iter: this) => boolean, context?: unknown) => this;
Returns a new Collection of the same type which includes entries from this Collection as long as the
predicate
returns true.<!-- runkit:activate -->
const { List } = require('immutable')List([ 'dog', 'frog', 'cat', 'hat', 'god' ]).takeWhile(x => x.match(/o/))// List [ "dog", "frog" ]
method toArray
toArray: () => Array<V> | Array<[K, V]>;
Shallowly converts this collection to an Array.
Collection.Indexed
, andCollection.Set
produce an Array of values.Collection.Keyed
produce an Array of [key, value] tuples.
method toIndexedSeq
toIndexedSeq: () => Seq.Indexed<V>;
Returns an Seq.Indexed of the values of this Collection, discarding keys.
method toJS
toJS: () => | DeepCopy<V>[] | { [x: string]: DeepCopy<V>; [x: number]: DeepCopy<V>; [x: symbol]: DeepCopy<V>; };
Deeply converts this Collection to equivalent native JavaScript Array or Object.
Collection.Indexed
, andCollection.Set
becomeArray
, whileCollection.Keyed
becomeObject
, converting keys to Strings.
method toJSON
toJSON: () => V[] | { [x: string]: V; [x: number]: V; [x: symbol]: V };
Shallowly converts this Collection to equivalent native JavaScript Array or Object.
Collection.Indexed
, andCollection.Set
becomeArray
, whileCollection.Keyed
becomeObject
, converting keys to Strings.
method toKeyedSeq
toKeyedSeq: () => Seq.Keyed<K, V>;
Returns a Seq.Keyed from this Collection where indices are treated as keys.
This is useful if you want to operate on an Collection.Indexed and preserve the [index, value] pairs.
The returned Seq will have identical iteration order as this Collection.
<!-- runkit:activate -->
const { Seq } = require('immutable')const indexedSeq = Seq([ 'A', 'B', 'C' ])// Seq [ "A", "B", "C" ]indexedSeq.filter(v => v === 'B')// Seq [ "B" ]const keyedSeq = indexedSeq.toKeyedSeq()// Seq { 0: "A", 1: "B", 2: "C" }keyedSeq.filter(v => v === 'B')// Seq { 1: "B" }
method toList
toList: () => List<V>;
Converts this Collection to a List, discarding keys.
This is similar to
List(collection)
, but provided to allow for chained expressions. However, when called onMap
or other keyed collections,collection.toList()
discards the keys and creates a list of only the values, whereasList(collection)
creates a list of entry tuples.<!-- runkit:activate -->
const { Map, List } = require('immutable')var myMap = Map({ a: 'Apple', b: 'Banana' })List(myMap) // List [ [ "a", "Apple" ], [ "b", "Banana" ] ]myMap.toList() // List [ "Apple", "Banana" ]
method toMap
toMap: () => Map<K, V>;
Converts this Collection to a Map, Throws if keys are not hashable.
Note: This is equivalent to
Map(this.toKeyedSeq())
, but provided for convenience and to allow for chained expressions.
method toObject
toObject: () => { [key: string]: V };
Shallowly converts this Collection to an Object.
Converts keys to Strings.
method toOrderedMap
toOrderedMap: () => OrderedMap<K, V>;
Converts this Collection to a Map, maintaining the order of iteration.
Note: This is equivalent to
OrderedMap(this.toKeyedSeq())
, but provided for convenience and to allow for chained expressions.
method toOrderedSet
toOrderedSet: () => OrderedSet<V>;
Converts this Collection to a Set, maintaining the order of iteration and discarding keys.
Note: This is equivalent to
OrderedSet(this.valueSeq())
, but provided for convenience and to allow for chained expressions.
method toSeq
toSeq: () => Seq<K, V>;
Converts this Collection to a Seq of the same kind (indexed, keyed, or set).
method toSet
toSet: () => Set<V>;
Converts this Collection to a Set, discarding keys. Throws if values are not hashable.
Note: This is equivalent to
Set(this)
, but provided to allow for chained expressions.
method toSetSeq
toSetSeq: () => Seq.Set<V>;
Returns a Seq.Set of the values of this Collection, discarding keys.
method toStack
toStack: () => Stack<V>;
Converts this Collection to a Stack, discarding keys. Throws if values are not hashable.
Note: This is equivalent to
Stack(this)
, but provided to allow for chained expressions.
method update
update: <R>(updater: (value: this) => R) => R;
This can be very useful as a way to "chain" a normal function into a sequence of methods. RxJS calls this "let" and lodash calls it "thru".
For example, to sum a Seq after mapping and filtering:
<!-- runkit:activate -->
const { Seq } = require('immutable')function sum(collection) {return collection.reduce((sum, x) => sum + x, 0)}Seq([ 1, 2, 3 ]).map(x => x + 1).filter(x => x % 2 === 0).update(sum)// 6
method values
values: () => IterableIterator<V>;
An iterator of this
Collection
's values.Note: this will return an ES6 iterator which does not support Immutable.js sequence algorithms. Use
valueSeq
instead, if this is what you want.
method valueSeq
valueSeq: () => Seq.Indexed<V>;
Returns an Seq.Indexed of the values of this Collection, discarding keys.
interface List
interface List<T> extends Collection.Indexed<T> {}
property size
readonly size: number;
The number of items in this List.
method asImmutable
asImmutable: () => this;
See Also
Map#asImmutable
method asMutable
asMutable: () => this;
An alternative API for withMutations()
Note: Not all methods can be safely used on a mutable collection or within
withMutations
! Check the documentation for each method to see if it allows being used inwithMutations
.See Also
Map#asMutable
method clear
clear: () => List<T>;
Returns a new List with 0 size and no values in constant time.
<!-- runkit:activate { "preamble": "const { List } = require('immutable');" } -->
List([ 1, 2, 3, 4 ]).clear()// List []Note:
clear
can be used inwithMutations
.
method concat
concat: <C>(...valuesOrCollections: Array<Iterable<C> | C>) => List<T | C>;
Returns a new List with other values or collections concatenated to this one.
Note:
concat
can be used inwithMutations
.merge
method delete
delete: (index: number) => List<T>;
Returns a new List which excludes this
index
and with a size 1 less than this List. Values at indices aboveindex
are shifted down by 1 to fill the position.This is synonymous with
list.splice(index, 1)
.index
may be a negative number, which indexes back from the end of the List.v.delete(-1)
deletes the last item in the List.Note:
delete
cannot be safely used in IE8<!-- runkit:activate { "preamble": "const { List } = require('immutable');" } -->
List([ 0, 1, 2, 3, 4 ]).delete(0);// List [ 1, 2, 3, 4 ]Since
delete()
re-indexes values, it produces a complete copy, which hasO(N)
complexity.Note:
delete
*cannot* be used inwithMutations
.remove
method deleteIn
deleteIn: (keyPath: Iterable<unknown>) => this;
Returns a new List having removed the value at this
keyPath
. If any keys inkeyPath
do not exist, no change will occur.<!-- runkit:activate -->
const { List } = require('immutable')const list = List([ 0, 1, 2, List([ 3, 4 ])])list.deleteIn([3, 0]);// List [ 0, 1, 2, List [ 4 ] ]Plain JavaScript Object or Arrays may be nested within an Immutable.js Collection, and removeIn() can update those values as well, treating them immutably by creating new copies of those values with the changes applied.
<!-- runkit:activate -->
const { List } = require('immutable')const list = List([ 0, 1, 2, { plain: 'object' }])list.removeIn([3, 'plain']);// List([ 0, 1, 2, {}])Note:
deleteIn
*cannot* be safely used inwithMutations
.removeIn
method filter
filter: { <F extends T>( predicate: (value: T, index: number, iter: this) => value is F, context?: unknown ): List<F>; ( predicate: (value: T, index: number, iter: this) => unknown, context?: unknown ): this;};
Returns a new List with only the values for which the
predicate
function returns true.Note:
filter()
always returns a new instance, even if it results in not filtering out any values.
method flatMap
flatMap: <M>( mapper: (value: T, key: number, iter: this) => Iterable<M>, context?: unknown) => List<M>;
Flat-maps the List, returning a new List.
Similar to
list.map(...).flatten(true)
.
method insert
insert: (index: number, value: T) => List<T>;
Returns a new List with
value
atindex
with a size 1 more than this List. Values at indices aboveindex
are shifted over by 1.This is synonymous with
list.splice(index, 0, value)
.<!-- runkit:activate { "preamble": "const { List } = require('immutable');" } -->
List([ 0, 1, 2, 3, 4 ]).insert(6, 5)// List [ 0, 1, 2, 3, 4, 5 ]Since
insert()
re-indexes values, it produces a complete copy, which hasO(N)
complexity.Note:
insert
*cannot* be used inwithMutations
.
method map
map: <M>( mapper: (value: T, key: number, iter: this) => M, context?: unknown) => List<M>;
Returns a new List with values passed through a
mapper
function.<!-- runkit:activate { "preamble": "const { List } = require('immutable');" } -->
List([ 1, 2 ]).map(x => 10 * x)// List [ 10, 20 ]
method merge
merge: <C>(...collections: Array<Iterable<C>>) => List<T | C>;
method mergeDeepIn
mergeDeepIn: ( keyPath: Iterable<unknown>, ...collections: Array<unknown>) => this;
Note:
mergeDeepIn
can be used inwithMutations
.See Also
Map#mergeDeepIn
method mergeIn
mergeIn: (keyPath: Iterable<unknown>, ...collections: Array<unknown>) => this;
Note:
mergeIn
can be used inwithMutations
.See Also
Map#mergeIn
method partition
partition: { <F extends T, C>( predicate: (this: C, value: T, index: number, iter: this) => value is F, context?: C ): [List<T>, List<F>]; <C>( predicate: (this: C, value: T, index: number, iter: this) => unknown, context?: C ): [this, this];};
Returns a new List with the values for which the
predicate
function returns false and another for which is returns true.
method pop
pop: () => List<T>;
Returns a new List with a size ones less than this List, excluding the last index in this List.
Note: this differs from
Array#pop
because it returns a new List rather than the removed value. Uselast()
to get the last value in this List.List([ 1, 2, 3, 4 ]).pop()// List[ 1, 2, 3 ]Note:
pop
can be used inwithMutations
.
method push
push: (...values: Array<T>) => List<T>;
Returns a new List with the provided
values
appended, starting at this List'ssize
.<!-- runkit:activate { "preamble": "const { List } = require('immutable');" } -->
List([ 1, 2, 3, 4 ]).push(5)// List [ 1, 2, 3, 4, 5 ]Note:
push
can be used inwithMutations
.
method remove
remove: (index: number) => List<T>;
method removeIn
removeIn: (keyPath: Iterable<unknown>) => this;
method set
set: (index: number, value: T) => List<T>;
Returns a new List which includes
value
atindex
. Ifindex
already exists in this List, it will be replaced.index
may be a negative number, which indexes back from the end of the List.v.set(-1, "value")
sets the last item in the List.If
index
larger thansize
, the returned List'ssize
will be large enough to include theindex
.<!-- runkit:activate { "preamble": "const { List } = require('immutable');" } -->
const originalList = List([ 0 ]);// List [ 0 ]originalList.set(1, 1);// List [ 0, 1 ]originalList.set(0, 'overwritten');// List [ "overwritten" ]originalList.set(2, 2);// List [ 0, undefined, 2 ]List().set(50000, 'value').size;// 50001Note:
set
can be used inwithMutations
.
method setIn
setIn: (keyPath: Iterable<unknown>, value: unknown) => this;
Returns a new List having set
value
at thiskeyPath
. If any keys inkeyPath
do not exist, a new immutable Map will be created at that key.Index numbers are used as keys to determine the path to follow in the List.
<!-- runkit:activate -->
const { List } = require('immutable')const list = List([ 0, 1, 2, List([ 3, 4 ])])list.setIn([3, 0], 999);// List [ 0, 1, 2, List [ 999, 4 ] ]Plain JavaScript Object or Arrays may be nested within an Immutable.js Collection, and setIn() can update those values as well, treating them immutably by creating new copies of those values with the changes applied.
<!-- runkit:activate -->
const { List } = require('immutable')const list = List([ 0, 1, 2, { plain: 'object' }])list.setIn([3, 'plain'], 'value');// List([ 0, 1, 2, { plain: 'value' }])Note:
setIn
can be used inwithMutations
.
method setSize
setSize: (size: number) => List<T>;
Returns a new List with size
size
. Ifsize
is less than this List's size, the new List will exclude values at the higher indices. Ifsize
is greater than this List's size, the new List will have undefined values for the newly available indices.When building a new List and the final size is known up front,
setSize
used in conjunction withwithMutations
may result in the more performant construction.
method shift
shift: () => List<T>;
Returns a new List with a size ones less than this List, excluding the first index in this List, shifting all other values to a lower index.
Note: this differs from
Array#shift
because it returns a new List rather than the removed value. Usefirst()
to get the first value in this List.<!-- runkit:activate { "preamble": "const { List } = require('immutable');" } -->
List([ 0, 1, 2, 3, 4 ]).shift();// List [ 1, 2, 3, 4 ]Note:
shift
can be used inwithMutations
.
method unshift
unshift: (...values: Array<T>) => List<T>;
Returns a new List with the provided
values
prepended, shifting other values ahead to higher indices.<!-- runkit:activate { "preamble": "const { List } = require('immutable');" } -->
List([ 2, 3, 4]).unshift(1);// List [ 1, 2, 3, 4 ]Note:
unshift
can be used inwithMutations
.
method update
update: { (index: number, notSetValue: T, updater: (value: T) => T): this; (index: number, updater: (value: T) => T): this; <R>(updater: (value: this) => R): R;};
Returns a new List with an updated value at
index
with the return value of callingupdater
with the existing value, ornotSetValue
ifindex
was not set. If called with a single argument,updater
is called with the List itself.index
may be a negative number, which indexes back from the end of the List.v.update(-1)
updates the last item in the List.<!-- runkit:activate { "preamble": "const { List } = require('immutable');" } -->
const list = List([ 'a', 'b', 'c' ])const result = list.update(2, val => val.toUpperCase())// List [ "a", "b", "C" ]This can be very useful as a way to "chain" a normal function into a sequence of methods. RxJS calls this "let" and lodash calls it "thru".
For example, to sum a List after mapping and filtering:
<!-- runkit:activate { "preamble": "const { List } = require('immutable');" } -->
function sum(collection) {return collection.reduce((sum, x) => sum + x, 0)}List([ 1, 2, 3 ]).map(x => x + 1).filter(x => x % 2 === 0).update(sum)// 6Note:
update(index)
can be used inwithMutations
.See Also
Map#update
method updateIn
updateIn: { ( keyPath: Iterable<unknown>, notSetValue: unknown, updater: (value: unknown) => unknown ): this; (keyPath: Iterable<unknown>, updater: (value: unknown) => unknown): this;};
Note:
updateIn
can be used inwithMutations
.See Also
Map#updateIn
method wasAltered
wasAltered: () => boolean;
See Also
Map#wasAltered
method withMutations
withMutations: (mutator: (mutable: this) => unknown) => this;
Note: Not all methods can be safely used on a mutable collection or within
withMutations
! Check the documentation for each method to see if it allows being used inwithMutations
.See Also
Map#withMutations
method zip
zip: { <U>(other: Collection<unknown, U>): List<[T, U]>; <U, V>(other: Collection<unknown, U>, other2: Collection<unknown, V>): List< [T, U, V] >; (...collections: Collection<unknown, unknown>[]): List<unknown>;};
Returns a List "zipped" with the provided collection.
Like
zipWith
, but using the defaultzipper
: creating anArray
.<!-- runkit:activate { "preamble": "const { List } = require('immutable');" } -->
const a = List([ 1, 2, 3 ]);const b = List([ 4, 5, 6 ]);const c = a.zip(b); // List [ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ]
method zipAll
zipAll: { <U>(other: Collection<unknown, U>): List<[T, U]>; <U, V>(other: Collection<unknown, U>, other2: Collection<unknown, V>): List< [T, U, V] >; (...collections: Collection<unknown, unknown>[]): List<unknown>;};
Returns a List "zipped" with the provided collections.
Unlike
zip
,zipAll
continues zipping until the longest collection is exhausted. Missing values from shorter collections are filled withundefined
.<!-- runkit:activate { "preamble": "const { List } = require('immutable');" } -->
const a = List([ 1, 2 ]);const b = List([ 3, 4, 5 ]);const c = a.zipAll(b); // List [ [ 1, 3 ], [ 2, 4 ], [ undefined, 5 ] ]Note: Since zipAll will return a collection as large as the largest input, some results may contain undefined values. TypeScript cannot account for these without cases (as of v2.5).
method zipWith
zipWith: { <U, Z>( zipper: (value: T, otherValue: U) => Z, otherCollection: Collection<unknown, U> ): List<Z>; <U, V, Z>( zipper: (value: T, otherValue: U, thirdValue: V) => Z, otherCollection: Collection<unknown, U>, thirdCollection: Collection<unknown, V> ): List<Z>; <Z>( zipper: (...values: unknown[]) => Z, ...collections: Collection<unknown, unknown>[] ): List<Z>;};
Returns a List "zipped" with the provided collections by using a custom
zipper
function.<!-- runkit:activate { "preamble": "const { List } = require('immutable');" } -->
const a = List([ 1, 2, 3 ]);const b = List([ 4, 5, 6 ]);const c = a.zipWith((a, b) => a + b, b);// List [ 5, 7, 9 ]
interface Map
interface Map<K, V> extends Collection.Keyed<K, V> {}
property size
readonly size: number;
The number of entries in this Map.
method asImmutable
asImmutable: () => this;
The yin to
asMutable
's yang. Because it applies to mutable collections, this operation is *mutable* and may return itself (though may not return itself, i.e. if the result is an empty collection). Once performed, the original mutable copy must no longer be mutated since it may be the immutable result.If possible, use
withMutations
to work with temporary mutable copies as it provides an easier to use API and considers many common optimizations.See Also
Map#asMutable
method asMutable
asMutable: () => this;
Another way to avoid creation of intermediate Immutable maps is to create a mutable copy of this collection. Mutable copies *always* return
this
, and thus shouldn't be used for equality. Your function should never return a mutable copy of a collection, only use it internally to create a new collection.If possible, use
withMutations
to work with temporary mutable copies as it provides an easier to use API and considers many common optimizations.Note: if the collection is already mutable,
asMutable
returns itself.Note: Not all methods can be used on a mutable collection or within
withMutations
! Read the documentation for each method to see if it is safe to use inwithMutations
.See Also
Map#asImmutable
method clear
clear: () => this;
Returns a new Map containing no keys or values.
<!-- runkit:activate -->
const { Map } = require('immutable')Map({ key: 'value' }).clear()// Map {}Note:
clear
can be used inwithMutations
.
method concat
concat: { <KC, VC>(...collections: Array<Iterable<[KC, VC]>>): Map< K | KC, VC | Exclude<V, VC> >; <C>(...collections: { [key: string]: C }[]): Map< string | K, C | Exclude<V, C> >;};
method delete
delete: (key: K) => this;
Returns a new Map which excludes this
key
.Note:
delete
cannot be safely used in IE8, but is provided to mirror the ES6 collection API.<!-- runkit:activate -->
const { Map } = require('immutable')const originalMap = Map({key: 'value',otherKey: 'other value'})// Map { "key": "value", "otherKey": "other value" }originalMap.delete('otherKey')// Map { "key": "value" }Note:
delete
can be used inwithMutations
.remove
method deleteAll
deleteAll: (keys: Iterable<K>) => this;
Returns a new Map which excludes the provided
keys
.<!-- runkit:activate -->
const { Map } = require('immutable')const names = Map({ a: "Aaron", b: "Barry", c: "Connor" })names.deleteAll([ 'a', 'c' ])// Map { "b": "Barry" }Note:
deleteAll
can be used inwithMutations
.removeAll
method deleteIn
deleteIn: (keyPath: Iterable<unknown>) => this;
Returns a new Map having removed the value at this
keyPath
. If any keys inkeyPath
do not exist, no change will occur.Note:
deleteIn
can be used inwithMutations
.removeIn
method filter
filter: { <F extends V>( predicate: (value: V, key: K, iter: this) => value is F, context?: unknown ): Map<K, F>; ( predicate: (value: V, key: K, iter: this) => unknown, context?: unknown ): this;};
Returns a new Map with only the entries for which the
predicate
function returns true.Note:
filter()
always returns a new instance, even if it results in not filtering out any values.
method flatMap
flatMap: <KM, VM>( mapper: (value: V, key: K, iter: this) => Iterable<[KM, VM]>, context?: unknown) => Map<KM, VM>;
Flat-maps the Map, returning a new Map.
Similar to
data.map(...).flatten(true)
.
method flip
flip: () => Map<V, K>;
See Also
Collection.Keyed.flip
method map
map: <M>( mapper: (value: V, key: K, iter: this) => M, context?: unknown) => Map<K, M>;
Returns a new Map with values passed through a
mapper
function.Map({ a: 1, b: 2 }).map(x => 10 * x) // Map { a: 10, b: 20 }
method mapEntries
mapEntries: <KM, VM>( mapper: (entry: [K, V], index: number, iter: this) => [KM, VM] | undefined, context?: unknown) => Map<KM, VM>;
See Also
Collection.Keyed.mapEntries
method mapKeys
mapKeys: <M>( mapper: (key: K, value: V, iter: this) => M, context?: unknown) => Map<M, V>;
See Also
Collection.Keyed.mapKeys
method merge
merge: { <KC, VC>(...collections: Array<Iterable<[KC, VC]>>): Map< K | KC, VC | Exclude<V, VC> >; <C>(...collections: { [key: string]: C }[]): Map< string | K, C | Exclude<V, C> >;};
Returns a new Map resulting from merging the provided Collections (or JS objects) into this Map. In other words, this takes each entry of each collection and sets it on this Map.
Note: Values provided to
merge
are shallowly converted before being merged. No nested values are altered.<!-- runkit:activate -->
const { Map } = require('immutable')const one = Map({ a: 10, b: 20, c: 30 })const two = Map({ b: 40, a: 50, d: 60 })one.merge(two) // Map { "a": 50, "b": 40, "c": 30, "d": 60 }two.merge(one) // Map { "b": 20, "a": 10, "d": 60, "c": 30 }Note:
merge
can be used inwithMutations
.concat
method mergeDeep
mergeDeep: { <KC, VC>(...collections: Array<Iterable<[KC, VC]>>): Map<K | KC, V | VC>; <C>(...collections: { [key: string]: C }[]): Map<string | K, V | C>;};
Like
merge()
, but when two compatible collections are encountered with the same key, it merges them as well, recursing deeply through the nested data. Two collections are considered to be compatible (and thus will be merged together) if they both fall into one of three categories: keyed (e.g.,Map
s,Record
s, and objects), indexed (e.g.,List
s and arrays), or set-like (e.g.,Set
s). If they fall into separate categories,mergeDeep
will replace the existing collection with the collection being merged in. This behavior can be customized by usingmergeDeepWith()
.Note: Indexed and set-like collections are merged using
concat()
/union()
and therefore do not recurse.<!-- runkit:activate -->
const { Map } = require('immutable')const one = Map({ a: Map({ x: 10, y: 10 }), b: Map({ x: 20, y: 50 }) })const two = Map({ a: Map({ x: 2 }), b: Map({ y: 5 }), c: Map({ z: 3 }) })one.mergeDeep(two)// Map {// "a": Map { "x": 2, "y": 10 },// "b": Map { "x": 20, "y": 5 },// "c": Map { "z": 3 }// }Note:
mergeDeep
can be used inwithMutations
.
method mergeDeepIn
mergeDeepIn: ( keyPath: Iterable<unknown>, ...collections: Array<unknown>) => this;
A combination of
updateIn
andmergeDeep
, returning a new Map, but performing the deep merge at a point arrived at by following the keyPath. In other words, these two lines are equivalent:map.updateIn(['a', 'b', 'c'], abc => abc.mergeDeep(y))map.mergeDeepIn(['a', 'b', 'c'], y)Note:
mergeDeepIn
can be used inwithMutations
.
method mergeDeepWith
mergeDeepWith: ( merger: (oldVal: unknown, newVal: unknown, key: unknown) => unknown, ...collections: (Iterable<[K, V]> | { [key: string]: V })[]) => this;
Like
mergeDeep()
, but when two non-collections or incompatible collections are encountered at the same key, it uses themerger
function to determine the resulting value. Collections are considered incompatible if they fall into separate categories between keyed, indexed, and set-like.<!-- runkit:activate -->
const { Map } = require('immutable')const one = Map({ a: Map({ x: 10, y: 10 }), b: Map({ x: 20, y: 50 }) })const two = Map({ a: Map({ x: 2 }), b: Map({ y: 5 }), c: Map({ z: 3 }) })one.mergeDeepWith((oldVal, newVal) => oldVal / newVal, two)// Map {// "a": Map { "x": 5, "y": 10 },// "b": Map { "x": 20, "y": 10 },// "c": Map { "z": 3 }// }Note:
mergeDeepWith
can be used inwithMutations
.
method mergeIn
mergeIn: (keyPath: Iterable<unknown>, ...collections: Array<unknown>) => this;
A combination of
updateIn
andmerge
, returning a new Map, but performing the merge at a point arrived at by following the keyPath. In other words, these two lines are equivalent:map.updateIn(['a', 'b', 'c'], abc => abc.merge(y))map.mergeIn(['a', 'b', 'c'], y)Note:
mergeIn
can be used inwithMutations
.
method mergeWith
mergeWith: { <KC, VC, VCC>( merger: (oldVal: V, newVal: VC, key: K) => VCC, ...collections: Array<Iterable<[KC, VC]>> ): Map<K | KC, V | VC | VCC>; <C, CC>( merger: (oldVal: V, newVal: C, key: string) => CC, ...collections: { [key: string]: C }[] ): Map<string | K, V | C | CC>;};
Like
merge()
,mergeWith()
returns a new Map resulting from merging the provided Collections (or JS objects) into this Map, but uses themerger
function for dealing with conflicts.<!-- runkit:activate -->
const { Map } = require('immutable')const one = Map({ a: 10, b: 20, c: 30 })const two = Map({ b: 40, a: 50, d: 60 })one.mergeWith((oldVal, newVal) => oldVal / newVal, two)// { "a": 0.2, "b": 0.5, "c": 30, "d": 60 }two.mergeWith((oldVal, newVal) => oldVal / newVal, one)// { "b": 2, "a": 5, "d": 60, "c": 30 }Note:
mergeWith
can be used inwithMutations
.
method partition
partition: { <F extends V, C>( predicate: (this: C, value: V, key: K, iter: this) => value is F, context?: C ): [Map<K, V>, Map<K, F>]; <C>( predicate: (this: C, value: V, key: K, iter: this) => unknown, context?: C ): [this, this];};
Returns a new Map with the values for which the
predicate
function returns false and another for which is returns true.
method remove
remove: (key: K) => this;
method removeAll
removeAll: (keys: Iterable<K>) => this;
method removeIn
removeIn: (keyPath: Iterable<unknown>) => this;
method set
set: (key: K, value: V) => this;
Returns a new Map also containing the new key, value pair. If an equivalent key already exists in this Map, it will be replaced.
<!-- runkit:activate -->
const { Map } = require('immutable')const originalMap = Map()const newerMap = originalMap.set('key', 'value')const newestMap = newerMap.set('key', 'newer value')originalMap// Map {}newerMap// Map { "key": "value" }newestMap// Map { "key": "newer value" }Note:
set
can be used inwithMutations
.
method setIn
setIn: (keyPath: Iterable<unknown>, value: unknown) => this;
Returns a new Map having set
value
at thiskeyPath
. If any keys inkeyPath
do not exist, a new immutable Map will be created at that key.<!-- runkit:activate -->
const { Map } = require('immutable')const originalMap = Map({subObject: Map({subKey: 'subvalue',subSubObject: Map({subSubKey: 'subSubValue'})})})const newMap = originalMap.setIn(['subObject', 'subKey'], 'ha ha!')// Map {// "subObject": Map {// "subKey": "ha ha!",// "subSubObject": Map { "subSubKey": "subSubValue" }// }// }const newerMap = originalMap.setIn(['subObject', 'subSubObject', 'subSubKey'],'ha ha ha!')// Map {// "subObject": Map {// "subKey": "subvalue",// "subSubObject": Map { "subSubKey": "ha ha ha!" }// }// }Plain JavaScript Object or Arrays may be nested within an Immutable.js Collection, and setIn() can update those values as well, treating them immutably by creating new copies of those values with the changes applied.
<!-- runkit:activate -->
const { Map } = require('immutable')const originalMap = Map({subObject: {subKey: 'subvalue',subSubObject: {subSubKey: 'subSubValue'}}})originalMap.setIn(['subObject', 'subKey'], 'ha ha!')// Map {// "subObject": {// subKey: "ha ha!",// subSubObject: { subSubKey: "subSubValue" }// }// }If any key in the path exists but cannot be updated (such as a primitive like number or a custom Object like Date), an error will be thrown.
Note:
setIn
can be used inwithMutations
.
method sort
sort: (comparator?: Comparator<V>) => this & OrderedMap<K, V>;
Returns an OrderedMap of the same type which includes the same entries, stably sorted by using a
comparator
.If a
comparator
is not provided, a default comparator uses<
and>
.comparator(valueA, valueB)
:* Returns
0
if the elements should not be swapped. * Returns-1
(or any negative number) ifvalueA
comes beforevalueB
* Returns1
(or any positive number) ifvalueA
comes aftervalueB
* Alternatively, can return a value of thePairSorting
enum type * Is pure, i.e. it must always return the same value for the same pair of values.<!-- runkit:activate -->
const { Map } = require('immutable')Map({ "c": 3, "a": 1, "b": 2 }).sort((a, b) => {if (a < b) { return -1; }if (a > b) { return 1; }if (a === b) { return 0; }});// OrderedMap { "a": 1, "b": 2, "c": 3 }Note:
sort()
Always returns a new instance, even if the original was already sorted.Note: This is always an eager operation.
method sortBy
sortBy: <C>( comparatorValueMapper: (value: V, key: K, iter: this) => C, comparator?: (valueA: C, valueB: C) => number) => this & OrderedMap<K, V>;
Like
sort
, but also accepts acomparatorValueMapper
which allows for sorting by more sophisticated means:<!-- runkit:activate -->
const { Map } = require('immutable')const beattles = Map({John: { name: "Lennon" },Paul: { name: "McCartney" },George: { name: "Harrison" },Ringo: { name: "Starr" },});beattles.sortBy(member => member.name);Note:
sortBy()
Always returns a new instance, even if the original was already sorted.Note: This is always an eager operation.
method update
update: { (key: K, notSetValue: V, updater: (value: V) => V): this; (key: K, updater: (value: V) => V): this; <R>(updater: (value: this) => R): R;};
Returns a new Map having updated the value at this
key
with the return value of callingupdater
with the existing value.Similar to:
map.set(key, updater(map.get(key)))
.<!-- runkit:activate -->
const { Map } = require('immutable')const aMap = Map({ key: 'value' })const newMap = aMap.update('key', value => value + value)// Map { "key": "valuevalue" }This is most commonly used to call methods on collections within a structure of data. For example, in order to
.push()
onto a nestedList
,update
andpush
can be used together:<!-- runkit:activate { "preamble": "const { Map, List } = require('immutable');" } -->
const aMap = Map({ nestedList: List([ 1, 2, 3 ]) })const newMap = aMap.update('nestedList', list => list.push(4))// Map { "nestedList": List [ 1, 2, 3, 4 ] }When a
notSetValue
is provided, it is provided to theupdater
function when the value at the key does not exist in the Map.<!-- runkit:activate { "preamble": "const { Map } = require('immutable');" } -->
const aMap = Map({ key: 'value' })const newMap = aMap.update('noKey', 'no value', value => value + value)// Map { "key": "value", "noKey": "no valueno value" }However, if the
updater
function returns the same value it was called with, then no change will occur. This is still true ifnotSetValue
is provided.<!-- runkit:activate { "preamble": "const { Map } = require('immutable');" } -->
const aMap = Map({ apples: 10 })const newMap = aMap.update('oranges', 0, val => val)// Map { "apples": 10 }assert.strictEqual(newMap, map);For code using ES2015 or later, using
notSetValue
is discourged in favor of function parameter default values. This helps to avoid any potential confusion with identify functions as described above.The previous example behaves differently when written with default values:
<!-- runkit:activate { "preamble": "const { Map } = require('immutable');" } -->
const aMap = Map({ apples: 10 })const newMap = aMap.update('oranges', (val = 0) => val)// Map { "apples": 10, "oranges": 0 }If no key is provided, then the
updater
function return value is returned as well.<!-- runkit:activate { "preamble": "const { Map } = require('immutable');" } -->
const aMap = Map({ key: 'value' })const result = aMap.update(aMap => aMap.get('key'))// "value"This can be very useful as a way to "chain" a normal function into a sequence of methods. RxJS calls this "let" and lodash calls it "thru".
For example, to sum the values in a Map
<!-- runkit:activate { "preamble": "const { Map } = require('immutable');" } -->
function sum(collection) {return collection.reduce((sum, x) => sum + x, 0)}Map({ x: 1, y: 2, z: 3 }).map(x => x + 1).filter(x => x % 2 === 0).update(sum)// 6Note:
update(key)
can be used inwithMutations
.
method updateIn
updateIn: { ( keyPath: Iterable<unknown>, notSetValue: unknown, updater: (value: unknown) => unknown ): this; (keyPath: Iterable<unknown>, updater: (value: unknown) => unknown): this;};
Returns a new Map having applied the
updater
to the entry found at the keyPath.This is most commonly used to call methods on collections nested within a structure of data. For example, in order to
.push()
onto a nestedList
,updateIn
andpush
can be used together:<!-- runkit:activate -->
const { Map, List } = require('immutable')const map = Map({ inMap: Map({ inList: List([ 1, 2, 3 ]) }) })const newMap = map.updateIn(['inMap', 'inList'], list => list.push(4))// Map { "inMap": Map { "inList": List [ 1, 2, 3, 4 ] } }If any keys in
keyPath
do not exist, new ImmutableMap
s will be created at those keys. If thekeyPath
does not already contain a value, theupdater
function will be called withnotSetValue
, if provided, otherwiseundefined
.<!-- runkit:activate { "preamble": "const { Map } = require('immutable')" } -->
const map = Map({ a: Map({ b: Map({ c: 10 }) }) })const newMap = map.updateIn(['a', 'b', 'c'], val => val * 2)// Map { "a": Map { "b": Map { "c": 20 } } }If the
updater
function returns the same value it was called with, then no change will occur. This is still true ifnotSetValue
is provided.<!-- runkit:activate { "preamble": "const { Map } = require('immutable')" } -->
const map = Map({ a: Map({ b: Map({ c: 10 }) }) })const newMap = map.updateIn(['a', 'b', 'x'], 100, val => val)// Map { "a": Map { "b": Map { "c": 10 } } }assert.strictEqual(newMap, aMap)For code using ES2015 or later, using
notSetValue
is discourged in favor of function parameter default values. This helps to avoid any potential confusion with identify functions as described above.The previous example behaves differently when written with default values:
<!-- runkit:activate { "preamble": "const { Map } = require('immutable')" } -->
const map = Map({ a: Map({ b: Map({ c: 10 }) }) })const newMap = map.updateIn(['a', 'b', 'x'], (val = 100) => val)// Map { "a": Map { "b": Map { "c": 10, "x": 100 } } }Plain JavaScript Object or Arrays may be nested within an Immutable.js Collection, and updateIn() can update those values as well, treating them immutably by creating new copies of those values with the changes applied.
<!-- runkit:activate { "preamble": "const { Map } = require('immutable')" } -->
const map = Map({ a: { b: { c: 10 } } })const newMap = map.updateIn(['a', 'b', 'c'], val => val * 2)// Map { "a": { b: { c: 20 } } }If any key in the path exists but cannot be updated (such as a primitive like number or a custom Object like Date), an error will be thrown.
Note:
updateIn
can be used inwithMutations
.
method wasAltered
wasAltered: () => boolean;
Returns true if this is a mutable copy (see
asMutable()
) and mutative alterations have been applied.See Also
Map#asMutable
method withMutations
withMutations: (mutator: (mutable: this) => unknown) => this;
Every time you call one of the above functions, a new immutable Map is created. If a pure function calls a number of these to produce a final return value, then a penalty on performance and memory has been paid by creating all of the intermediate immutable Maps.
If you need to apply a series of mutations to produce a new immutable Map,
withMutations()
creates a temporary mutable copy of the Map which can apply mutations in a highly performant manner. In fact, this is exactly how complex mutations likemerge
are done.As an example, this results in the creation of 2, not 4, new Maps:
<!-- runkit:activate -->
const { Map } = require('immutable')const map1 = Map()const map2 = map1.withMutations(map => {map.set('a', 1).set('b', 2).set('c', 3)})assert.equal(map1.size, 0)assert.equal(map2.size, 3)Note: Not all methods can be used on a mutable collection or within
withMutations
! Read the documentation for each method to see if it is safe to use inwithMutations
.
interface MapOf
interface MapOf<R extends { [key in string | number | symbol]: unknown }> extends Map<keyof R, R[keyof R]> {}
Represent a Map constructed by an object
method delete
delete: <K extends keyof R>( key: K) => Extract<R[K], undefined> extends never ? never : this;
method get
get: { <K extends keyof R>(key: K, notSetValue?: unknown): R[K]; <NSV>(key: any, notSetValue: NSV): NSV;};
Returns the value associated with the provided key, or notSetValue if the Collection does not contain this key.
Note: it is possible a key may be associated with an
undefined
value, so ifnotSetValue
is not provided and this method returnsundefined
, that does not guarantee the key was not found.
method getIn
getIn: <P extends readonly (string | number | symbol)[]>( searchKeyPath: [...P], notSetValue?: unknown) => RetrievePath<R,