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, P>;
method remove
remove: <K extends keyof R>( key: K) => Extract<R[K], undefined> extends never ? never : this;
method set
set: <K extends keyof R>(key: K, value: R[K]) => this;
method toJS
toJS: () => { [K in keyof R]: DeepCopy<R[K]> };
method toJSON
toJSON: () => { [K in keyof R]: R[K] };
method update
update: { (updater: (value: this) => this): this; <K extends keyof R>(key: K, updater: (value: R[K]) => R[K]): this; <K extends keyof R, NSV extends R[K]>( key: K, notSetValue: NSV, updater: (value: R[K]) => R[K] ): this;};
interface OrderedMap
interface OrderedMap<K, V> extends Map<K, V> {}
property size
readonly size: number;
The number of entries in this OrderedMap.
method concat
concat: { <KC, VC>(...collections: Array<Iterable<[KC, VC]>>): OrderedMap< K | KC, VC | Exclude<V, VC> >; <C>(...collections: { [key: string]: C }[]): OrderedMap< string | K, C | Exclude<V, C> >;};
method filter
filter: { <F extends V>( predicate: (value: V, key: K, iter: this) => value is F, context?: unknown ): OrderedMap<K, F>; ( predicate: (value: V, key: K, iter: this) => unknown, context?: unknown ): this;};
Returns a new OrderedMap 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) => OrderedMap<KM, VM>;
Flat-maps the OrderedMap, returning a new OrderedMap.
Similar to
data.map(...).flatten(true)
.
method flip
flip: () => OrderedMap<V, K>;
See Also
Collection.Keyed.flip
method map
map: <M>( mapper: (value: V, key: K, iter: this) => M, context?: unknown) => OrderedMap<K, M>;
Returns a new OrderedMap with values passed through a
mapper
function.OrderedMap({ a: 1, b: 2 }).map(x => 10 * x) // OrderedMap { "a": 10, "b": 20 }
Note:
map()
always returns a new instance, even if it produced the same value at every step.
method mapEntries
mapEntries: <KM, VM>( mapper: (entry: [K, V], index: number, iter: this) => [KM, VM] | undefined, context?: unknown) => OrderedMap<KM, VM>;
See Also
Collection.Keyed.mapEntries
method mapKeys
mapKeys: <M>( mapper: (key: K, value: V, iter: this) => M, context?: unknown) => OrderedMap<M, V>;
See Also
Collection.Keyed.mapKeys
method merge
merge: { <KC, VC>(...collections: Array<Iterable<[KC, VC]>>): OrderedMap< K | KC, VC | Exclude<V, VC> >; <C>(...collections: { [key: string]: C }[]): OrderedMap< string | K, C | Exclude<V, C> >;};
Returns a new OrderedMap resulting from merging the provided Collections (or JS objects) into this OrderedMap. In other words, this takes each entry of each collection and sets it on this OrderedMap.
Note: Values provided to
merge
are shallowly converted before being merged. No nested values are altered.<!-- runkit:activate -->
const { OrderedMap } = require('immutable')const one = OrderedMap({ a: 10, b: 20, c: 30 })const two = OrderedMap({ b: 40, a: 50, d: 60 })one.merge(two) // OrderedMap { "a": 50, "b": 40, "c": 30, "d": 60 }two.merge(one) // OrderedMap { "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]>>): OrderedMap< K | KC, V | VC >; <C>(...collections: { [key: string]: C }[]): OrderedMap<string | K, V | C>;};
method mergeWith
mergeWith: { <KC, VC, VCC>( merger: (oldVal: V, newVal: VC, key: K) => VCC, ...collections: Array<Iterable<[KC, VC]>> ): OrderedMap<K | KC, V | VC | VCC>; <C, CC>( merger: (oldVal: V, newVal: C, key: string) => CC, ...collections: { [key: string]: C }[] ): OrderedMap<string | K, V | C | CC>;};
method partition
partition: { <F extends V, C>( predicate: (this: C, value: V, key: K, iter: this) => value is F, context?: C ): [OrderedMap<K, V>, OrderedMap<K, F>]; <C>( predicate: (this: C, value: V, key: K, iter: this) => unknown, context?: C ): [this, this];};
Returns a new OrderedMap with the values for which the
predicate
function returns false and another for which is returns true.
method set
set: (key: K, value: V) => this;
Returns a new OrderedMap also containing the new key, value pair. If an equivalent key already exists in this OrderedMap, it will be replaced while maintaining the existing order.
<!-- runkit:activate -->
const { OrderedMap } = require('immutable')const originalMap = OrderedMap({a:1, b:1, c:1})const updatedMap = originalMap.set('b', 2)originalMap// OrderedMap {a: 1, b: 1, c: 1}updatedMap// OrderedMap {a: 1, b: 2, c: 1}Note:
set
can be used inwithMutations
.
interface OrderedSet
interface OrderedSet<T> extends Set<T> {}
property size
readonly size: number;
The number of items in this OrderedSet.
method concat
concat: <C>(...collections: Array<Iterable<C>>) => OrderedSet<T | C>;
method filter
filter: { <F extends T>( predicate: (value: T, key: T, iter: this) => value is F, context?: unknown ): OrderedSet<F>; ( predicate: (value: T, key: T, iter: this) => unknown, context?: unknown ): this;};
Returns a new OrderedSet 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: T, iter: this) => Iterable<M>, context?: unknown) => OrderedSet<M>;
Flat-maps the OrderedSet, returning a new OrderedSet.
Similar to
set.map(...).flatten(true)
.
method map
map: <M>( mapper: (value: T, key: T, iter: this) => M, context?: unknown) => OrderedSet<M>;
Returns a new Set with values passed through a
mapper
function.OrderedSet([ 1, 2 ]).map(x => 10 * x) // OrderedSet [10, 20]
method merge
merge: <C>(...collections: Array<Iterable<C>>) => OrderedSet<T | C>;
method partition
partition: { <F extends T, C>( predicate: (this: C, value: T, key: T, iter: this) => value is F, context?: C ): [OrderedSet<T>, OrderedSet<F>]; <C>( predicate: (this: C, value: T, key: T, iter: this) => unknown, context?: C ): [this, this];};
Returns a new OrderedSet with the values for which the
predicate
function returns false and another for which is returns true.
method union
union: <C>(...collections: Array<Iterable<C>>) => OrderedSet<T | C>;
Returns an OrderedSet including any value from
collections
that does not already exist in this OrderedSet.Note:
union
can be used inwithMutations
. merge concat
method zip
zip: { <U>(other: Collection<unknown, U>): OrderedSet<[T, U]>; <U, V>( other1: Collection<unknown, U>, other2: Collection<unknown, V> ): OrderedSet<[T, U, V]>; (...collections: Collection<unknown, unknown>[]): OrderedSet<unknown>;};
Returns an OrderedSet of the same type "zipped" with the provided collections.
Like
zipWith
, but using the defaultzipper
: creating anArray
.const a = OrderedSet([ 1, 2, 3 ])const b = OrderedSet([ 4, 5, 6 ])const c = a.zip(b)// OrderedSet [ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ]
method zipAll
zipAll: { <U>(other: Collection<unknown, U>): OrderedSet<[T, U]>; <U, V>( other1: Collection<unknown, U>, other2: Collection<unknown, V> ): OrderedSet<[T, U, V]>; (...collections: Collection<unknown, unknown>[]): OrderedSet<unknown>;};
Returns a OrderedSet of the same type "zipped" with the provided collections.
Unlike
zip
,zipAll
continues zipping until the longest collection is exhausted. Missing values from shorter collections are filled withundefined
.const a = OrderedSet([ 1, 2 ]);const b = OrderedSet([ 3, 4, 5 ]);const c = a.zipAll(b); // OrderedSet [ [ 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> ): OrderedSet<Z>; <U, V, Z>( zipper: (value: T, otherValue: U, thirdValue: V) => Z, otherCollection: Collection<unknown, U>, thirdCollection: Collection<unknown, V> ): OrderedSet<Z>; <Z>( zipper: (...values: unknown[]) => Z, ...collections: Collection<unknown, unknown>[] ): OrderedSet<Z>;};
Returns an OrderedSet of the same type "zipped" with the provided collections by using a custom
zipper
function.See Also
Seq.Indexed.zipWith
interface Record
interface Record<TProps extends object> {}
method [Symbol.iterator]
[Symbol.iterator]: () => IterableIterator<[keyof TProps, TProps[keyof TProps]]>;
method asImmutable
asImmutable: () => this;
See Also
Map#asImmutable
method asMutable
asMutable: () => this;
See Also
Map#asMutable
method clear
clear: () => this;
Returns a new instance of this Record type with all values set to their default values.
method delete
delete: <K extends keyof TProps>(key: K) => this;
Returns a new instance of this Record type with the value for the specific key set to its default value.
remove
method deleteIn
deleteIn: (keyPath: Iterable<unknown>) => this;
removeIn
method equals
equals: (other: unknown) => boolean;
method get
get: { <K extends keyof TProps>(key: K, notSetValue?: unknown): TProps[K]; <T>(key: string, notSetValue: T): T;};
Returns the value associated with the provided key, which may be the default value defined when creating the Record factory function.
If the requested key is not defined by this Record type, then notSetValue will be returned if provided. Note that this scenario would produce an error when using Flow or TypeScript.
method getIn
getIn: (keyPath: Iterable<unknown>) => unknown;
method has
has: (key: string) => key is keyof TProps & string;
method hashCode
hashCode: () => number;
method hasIn
hasIn: (keyPath: Iterable<unknown>) => boolean;
method merge
merge: ( ...collections: Array<Partial<TProps> | Iterable<[string, unknown]>>) => this;
method mergeDeep
mergeDeep: ( ...collections: Array<Partial<TProps> | Iterable<[string, unknown]>>) => this;
method mergeDeepIn
mergeDeepIn: ( keyPath: Iterable<unknown>, ...collections: Array<unknown>) => this;
method mergeDeepWith
mergeDeepWith: ( merger: (oldVal: unknown, newVal: unknown, key: unknown) => unknown, ...collections: Array<Partial<TProps> | Iterable<[string, unknown]>>) => this;
method mergeIn
mergeIn: (keyPath: Iterable<unknown>, ...collections: Array<unknown>) => this;
method mergeWith
mergeWith: ( merger: (oldVal: unknown, newVal: unknown, key: keyof TProps) => unknown, ...collections: Array<Partial<TProps> | Iterable<[string, unknown]>>) => this;
method remove
remove: <K extends keyof TProps>(key: K) => this;
method removeIn
removeIn: (keyPath: Iterable<unknown>) => this;
method set
set: <K extends keyof TProps>(key: K, value: TProps[K]) => this;
method setIn
setIn: (keyPath: Iterable<unknown>, value: unknown) => this;
method toJS
toJS: () => DeepCopy<TProps>;
Deeply converts this Record to equivalent native JavaScript Object.
Note: This method may not be overridden. Objects with custom serialization to plain JS may override toJSON() instead.
method toJSON
toJSON: () => TProps;
Shallowly converts this Record to equivalent native JavaScript Object.
method toObject
toObject: () => TProps;
Shallowly converts this Record to equivalent JavaScript Object.
method toSeq
toSeq: () => Seq.Keyed<keyof TProps, TProps[keyof TProps]>;
method update
update: <K extends keyof TProps>( key: K, updater: (value: TProps[K]) => TProps[K]) => this;
method updateIn
updateIn: ( keyPath: Iterable<unknown>, updater: (value: unknown) => unknown) => this;
method wasAltered
wasAltered: () => boolean;
See Also
Map#wasAltered
method withMutations
withMutations: (mutator: (mutable: this) => unknown) => this;
Note: Not all methods can be used on a mutable collection or within
withMutations
! Onlyset
may be used mutatively.See Also
Map#withMutations
interface Seq
interface Seq<K, V> extends Collection<K, V> {}
property size
readonly size: number | undefined;
Some Seqs can describe their size lazily. When this is the case, size will be an integer. Otherwise it will be undefined.
For example, Seqs returned from
map()
orreverse()
preserve the size of the originalSeq
whilefilter()
does not.Note:
Range
,Repeat
andSeq
s made fromArray
s andObject
s will always have a size.
method cacheResult
cacheResult: () => this;
Because Sequences are lazy and designed to be chained together, they do not cache their results. For example, this map function is called a total of 6 times, as each
join
iterates the Seq of three values.var squares = Seq([ 1, 2, 3 ]).map(x => x * x) squares.join() + squares.join()
If you know a
Seq
will be used multiple times, it may be more efficient to first cache it in memory. Here, the map function is called only 3 times.var squares = Seq([ 1, 2, 3 ]).map(x => x * x).cacheResult() squares.join() + squares.join()
Use this method judiciously, as it must fully evaluate a Seq which can be a burden on memory and possibly performance.
Note: after calling
cacheResult
, a Seq will always have asize
.
method filter
filter: { <F extends V>( predicate: (value: V, key: K, iter: this) => value is F, context?: unknown ): Seq<K, F>; ( predicate: (value: V, key: K, iter: this) => unknown, context?: unknown ): this;};
Returns a new Seq 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: V, key: K, iter: this) => Iterable<M>, context?: unknown ): Seq<K, M>; <M>( mapper: (value: V, key: K, iter: this) => Iterable<M>, context?: unknown ): Seq<M, M>;};
Flat-maps the Seq, returning a Seq of the same type.
Similar to
seq.map(...).flatten(true)
.Flat-maps the Seq, returning a Seq of the same type.
Similar to
seq.map(...).flatten(true)
. Note: Used only for sets.
method map
map: { <M>(mapper: (value: V, key: K, iter: this) => M, context?: unknown): Seq< K, M >; <M>(mapper: (value: V, key: K, iter: this) => M, context?: unknown): Seq< M, M >;};
Returns a new Seq with values passed through a
mapper
function.const { Seq } = require('immutable')Seq([ 1, 2 ]).map(x => 10 * x)// Seq [ 10, 20 ]Note:
map()
always returns a new instance, even if it produced the same value at every step.Returns a new Seq with values passed through a
mapper
function.const { Seq } = require('immutable')Seq([ 1, 2 ]).map(x => 10 * x)// Seq [ 10, 20 ]Note:
map()
always returns a new instance, even if it produced the same value at every step. Note: used only for sets.
method partition
partition: { <F extends V, C>( predicate: (this: C, value: V, key: K, iter: this) => value is F, context?: C ): [Seq<K, V>, Seq<K, F>]; <C>( predicate: (this: C, value: V, key: K, iter: this) => unknown, context?: C ): [this, this];};
Returns a new Seq with the values for which the
predicate
function returns false and another for which is returns true.
interface Set
interface Set<T> extends Collection.Set<T> {}
property size
readonly size: number;
The number of items in this Set.
method add
add: (value: T) => this;
Returns a new Set which also includes this value.
Note:
add
can be used inwithMutations
.
method asImmutable
asImmutable: () => this;
See Also
Map#asImmutable
method asMutable
asMutable: () => this;
Note: Not all methods can be used on a mutable collection or within
withMutations
! Check the documentation for each method to see if it mentions being safe to use inwithMutations
.See Also
Map#asMutable
method clear
clear: () => this;
Returns a new Set containing no values.
Note:
clear
can be used inwithMutations
.
method concat
concat: <C>(...collections: Array<Iterable<C>>) => Set<T | C>;
method delete
delete: (value: T) => this;
Returns a new Set which excludes this value.
Note:
delete
can be used inwithMutations
.Note:
delete
**cannot** be safely used in IE8, useremove
if supporting old browsers.remove
method filter
filter: { <F extends T>( predicate: (value: T, key: T, iter: this) => value is F, context?: unknown ): Set<F>; ( predicate: (value: T, key: T, iter: this) => unknown, context?: unknown ): this;};
Returns a new Set 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: T, iter: this) => Iterable<M>, context?: unknown) => Set<M>;
Flat-maps the Set, returning a new Set.
Similar to
set.map(...).flatten(true)
.
method intersect
intersect: (...collections: Array<Iterable<T>>) => this;
Returns a Set which has removed any values not also contained within
collections
.Note:
intersect
can be used inwithMutations
.
method map
map: <M>( mapper: (value: T, key: T, iter: this) => M, context?: unknown) => Set<M>;
Returns a new Set with values passed through a
mapper
function.Set([1,2]).map(x => 10 * x) // Set [10,20]
method merge
merge: <C>(...collections: Array<Iterable<C>>) => Set<T | C>;
method partition
partition: { <F extends T, C>( predicate: (this: C, value: T, key: T, iter: this) => value is F, context?: C ): [Set<T>, Set<F>]; <C>( predicate: (this: C, value: T, key: T, iter: this) => unknown, context?: C ): [this, this];};
Returns a new Set with the values for which the
predicate
function returns false and another for which is returns true.
method remove
remove: (value: T) => this;
method sort
sort: (comparator?: Comparator<T>) => this & OrderedSet<T>;
Returns an OrderedSet 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 { Set } = require('immutable')Set(['b', 'a', 'c']).sort((a, b) => {if (a < b) { return -1; }if (a > b) { return 1; }if (a === b) { return 0; }});// OrderedSet { "a":, "b", "c" }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: T, key: T, iter: this) => C, comparator?: (valueA: C, valueB: C) => number) => this & OrderedSet<T>;
Like
sort
, but also accepts acomparatorValueMapper
which allows for sorting by more sophisticated means:<!-- runkit:activate -->
const { Set } = require('immutable')const beattles = Set([{ name: "Lennon" },{ name: "McCartney" },{ name: "Harrison" },{ 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 subtract
subtract: (...collections: Array<Iterable<T>>) => this;
Returns a Set excluding any values contained within
collections
.<!-- runkit:activate -->
const { OrderedSet } = require('immutable')OrderedSet([ 1, 2, 3 ]).subtract([1, 3])// OrderedSet [2]Note:
subtract
can be used inwithMutations
.
method union
union: <C>(...collections: Array<Iterable<C>>) => Set<T | C>;
Returns a Set including any value from
collections
that does not already exist in this Set.Note:
union
can be used inwithMutations
. merge concat
method wasAltered
wasAltered: () => boolean;
See Also
Map#wasAltered
method withMutations
withMutations: (mutator: (mutable: this) => unknown) => this;
Note: Not all methods can be used on a mutable collection or within
withMutations
! Check the documentation for each method to see if it mentions being safe to use inwithMutations
.See Also
Map#withMutations
interface Stack
interface Stack<T> extends Collection.Indexed<T> {}
property size
readonly size: number;
The number of items in this Stack.
method asImmutable
asImmutable: () => this;
See Also
Map#asImmutable
method asMutable
asMutable: () => this;
Note: Not all methods can be used on a mutable collection or within
withMutations
! Check the documentation for each method to see if it mentions being safe to use inwithMutations
.See Also
Map#asMutable
method clear
clear: () => Stack<T>;
Returns a new Stack with 0 size and no values.
Note:
clear
can be used inwithMutations
.
method concat
concat: <C>(...valuesOrCollections: Array<Iterable<C> | C>) => Stack<T | C>;
Returns a new Stack with other collections concatenated to this one.
method filter
filter: { <F extends T>( predicate: (value: T, index: number, iter: this) => value is F, context?: unknown ): Set<F>; ( predicate: (value: T, index: number, iter: this) => unknown, context?: unknown ): this;};
Returns a new Set 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) => Stack<M>;
Flat-maps the Stack, returning a new Stack.
Similar to
stack.map(...).flatten(true)
.
method map
map: <M>( mapper: (value: T, key: number, iter: this) => M, context?: unknown) => Stack<M>;
Returns a new Stack with values passed through a
mapper
function.Stack([ 1, 2 ]).map(x => 10 * x) // Stack [ 10, 20 ]
Note:
map()
always returns a new instance, even if it produced the same value at every step.
method peek
peek: () => T | undefined;
Alias for
Stack.first()
.
method pop
pop: () => Stack<T>;
Alias for
Stack#shift
and is not equivalent toList#pop
.
method push
push: (...values: Array<T>) => Stack<T>;
Alias for
Stack#unshift
and is not equivalent toList#push
.
method pushAll
pushAll: (iter: Iterable<T>) => Stack<T>;
Alias for
Stack#unshiftAll
.
method shift
shift: () => Stack<T>;
Returns a new Stack with a size ones less than this Stack, excluding the first item in this Stack, shifting all other values to a lower index.
Note: this differs from
Array#shift
because it returns a new Stack rather than the removed value. Usefirst()
orpeek()
to get the first value in this Stack.Note:
shift
can be used inwithMutations
.
method unshift
unshift: (...values: Array<T>) => Stack<T>;
Returns a new Stack with the provided
values
prepended, shifting other values ahead to higher indices.This is very efficient for Stack.
Note:
unshift
can be used inwithMutations
.
method unshiftAll
unshiftAll: (iter: Iterable<T>) => Stack<T>;
Like
Stack#unshift
, but accepts a collection rather than varargs.Note:
unshiftAll
can be used inwithMutations
.
method wasAltered
wasAltered: () => boolean;
See Also
Map#wasAltered
method withMutations
withMutations: (mutator: (mutable: this) => unknown) => this;
Note: Not all methods can be used on a mutable collection or within
withMutations
! Check the documentation for each method to see if it mentions being safe to use inwithMutations
.See Also
Map#withMutations
method zip
zip: { <U>(other: Collection<unknown, U>): Stack<[T, U]>; <U, V>(other: Collection<unknown, U>, other2: Collection<unknown, V>): Stack< [T, U, V] >; (...collections: Collection<unknown, unknown>[]): Stack<unknown>;};
Returns a Stack "zipped" with the provided collections.
Like
zipWith
, but using the defaultzipper
: creating anArray
.const a = Stack([ 1, 2, 3 ]);const b = Stack([ 4, 5, 6 ]);const c = a.zip(b); // Stack [ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ]
method zipAll
zipAll: { <U>(other: Collection<unknown, U>): Stack<[T, U]>; <U, V>(other: Collection<unknown, U>, other2: Collection<unknown, V>): Stack< [T, U, V] >; (...collections: Collection<unknown, unknown>[]): Stack<unknown>;};
Returns a Stack "zipped" with the provided collections.
Unlike
zip
,zipAll
continues zipping until the longest collection is exhausted. Missing values from shorter collections are filled withundefined
.const a = Stack([ 1, 2 ]);const b = Stack([ 3, 4, 5 ]);const c = a.zipAll(b); // Stack [ [ 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> ): Stack<Z>; <U, V, Z>( zipper: (value: T, otherValue: U, thirdValue: V) => Z, otherCollection: Collection<unknown, U>, thirdCollection: Collection<unknown, V> ): Stack<Z>; <Z>( zipper: (...values: unknown[]) => Z, ...collections: Collection<unknown, unknown>[] ): Stack<Z>;};
Returns a Stack "zipped" with the provided collections by using a custom
zipper
function.const a = Stack([ 1, 2, 3 ]);const b = Stack([ 4, 5, 6 ]);const c = a.zipWith((a, b) => a + b, b);// Stack [ 5, 7, 9 ]
interface ValueObject
interface ValueObject {}
The interface to fulfill to qualify as a Value Object.
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 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 -->
const { List, Set } = 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);Note: hashCode() MUST return a Uint32 number. The easiest way to guarantee this is to return
myHash | 0
from a custom implementation.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.Note:
hashCode()
is not guaranteed to always be called beforeequals()
. Most but not all Immutable.js collections use hash codes to organize their internal data structures, while all Immutable.js collections use equality during lookups.[Hash Collision]: https://en.wikipedia.org/wiki/Collision_(computer_science)
Enums
enum PairSorting
enum PairSorting { LeftThenRight = -1, RightThenLeft = +1,}
Describes which item in a pair should be placed first when sorting
member LeftThenRight
LeftThenRight = -1
member RightThenLeft
RightThenLeft = +1
Type Aliases
type Comparator
type Comparator<T> = (left: T, right: T) => PairSorting | number;
Function comparing two items of the same type. It can return:
* a PairSorting value, to indicate whether the left-hand item or the right-hand item should be placed before the other
* the traditional numeric return value - especially -1, 0, or 1
type ContainObject
type ContainObject<T> = OnlyObject<T> extends object ? OnlyObject<T> extends never ? false : true : false;
type DeepCopy
type DeepCopy<T> = T extends Record<infer R> ? // convert Record to DeepCopy plain JS object { [key in keyof R]: ContainObject<R[key]> extends true ? unknown : R[key]; } : T extends MapOf<infer R> ? // convert MapOf to DeepCopy plain JS object { [key in keyof R]: ContainObject<R[key]> extends true ? unknown : R[key]; } : T extends Collection.Keyed<infer KeyedKey, infer V> ? // convert KeyedCollection to DeepCopy plain JS object { [key in KeyedKey extends string | number | symbol ? KeyedKey : string]: V extends object ? unknown : V; } : // convert IndexedCollection or Immutable.Set to DeepCopy plain JS array // eslint-disable-next-line @typescript-eslint/no-unused-vars T extends Collection<infer _, infer V> ? Array<DeepCopy<V>> : T extends string | number // Iterable scalar types : should be kept as is ? T : T extends Iterable<infer V> // Iterable are converted to plain JS array ? Array<DeepCopy<V>> : T extends object // plain JS object are converted deeply ? { [ObjectKey in keyof T]: ContainObject<T[ObjectKey]> extends true ? unknown : T[ObjectKey]; } : // other case : should be kept as is T;
Used to convert deeply all immutable types to a plain TS type. Using
unknown
on object instead of recursive call as we have a circular reference issue
type FromJS
type FromJS<JSValue> = JSValue extends FromJSNoTransform ? JSValue : JSValue extends Array<any> ? FromJSArray<JSValue> : JSValue extends {} ? FromJSObject<JSValue> : any;
type FromJSArray
type FromJSArray<JSValue> = JSValue extends Array<infer T> ? List<FromJS<T>> : never;
type FromJSNoTransform
type FromJSNoTransform = Collection<any, any> | number | string | null | undefined;
type FromJSObject
type FromJSObject<JSValue> = JSValue extends {} ? Map<keyof JSValue, FromJS<JSValue[keyof JSValue]>> : never;
type GetMapType
type GetMapType<S> = S extends MapOf<infer T> ? T : S;
type Head
type Head<T extends ReadonlyArray<any>> = T extends [infer H, ...Array<unknown>] ? H : never;
type OnlyObject
type OnlyObject<T> = Extract<T, object>;
type RecordOf
type RecordOf<TProps extends object> = Record<TProps> & Readonly<TProps>;
RecordOf is used in TypeScript to define interfaces expecting an instance of record with type T.
This is equivalent to an instance of a record created by a Record Factory.
type RetrievePath
type RetrievePath< R, P extends ReadonlyArray<string | number | symbol>> = P extends [] ? P : RetrievePathReducer<R, Head<P>, Tail<P>>;
type RetrievePathReducer
type RetrievePathReducer< T, C, L extends ReadonlyArray<any>> = C extends keyof GetMapType<T> ? L extends [] ? GetMapType<T>[C] : RetrievePathReducer<GetMapType<T>[C], Head<L>, Tail<L>> : never;
type Tail
type Tail<T extends ReadonlyArray<any>> = T extends [unknown, ...infer I] ? I : Array<never>;
Namespaces
namespace Collection
namespace Collection {}
The
Collection
is a set of (key, value) entries which can be iterated, and is the base class for all collections inimmutable
, allowing them to make use of all the Collection methods (such asmap
andfilter
).Note: A collection is always iterated in the same order, however that order may not always be well defined, as is the case for the
Map
andSet
.Collection is the abstract base class for concrete data structures. It cannot be constructed directly.
Implementations should extend one of the subclasses,
Collection.Keyed
,Collection.Indexed
, orCollection.Set
.
function Indexed
Indexed: <T>(collection?: Iterable<T> | ArrayLike<T>) => Indexed<T>;
Creates a new Collection.Indexed.
Note:
Collection.Indexed
is a conversion function and not a class, and does not use thenew
keyword during construction.
function Keyed
Keyed: { <K, V>(collection?: Iterable<[K, V]>): Keyed<K, V>; <V>(obj: { [key: string]: V }): Keyed<string, V>;};
Creates a Collection.Keyed
Similar to
Collection()
, however it expects collection-likes of [K, V] tuples if not constructed from a Collection.Keyed or JS Object.Note:
Collection.Keyed
is a conversion function and not a class, and does not use thenew
keyword during construction.
function Set
Set: <T>(collection?: Iterable<T> | ArrayLike<T>) => Set<T>;
Similar to
Collection()
, but always returns a Collection.Set.Note:
Collection.Set
is a factory function and not a class, and does not use thenew
keyword during construction.
interface Indexed
interface Indexed<T> extends Collection<number, T> {}
method [Symbol.iterator]
[Symbol.iterator]: () => IterableIterator<T>;
method concat
concat: <C>(...valuesOrCollections: Array<Iterable<C> | C>) => Indexed<T | C>;
Returns a new Collection with other collections concatenated to this one.
method filter
filter: { <F extends T>( predicate: (value: T, index: number, iter: this) => value is F, context?: unknown ): Indexed<F>; ( predicate: (value: T, index: number, iter: this) => unknown, context?: unknown ): this;};
Returns a new Collection 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 findIndex
findIndex: ( predicate: (value: T, index: number, iter: this) => boolean, context?: unknown) => number;
Returns the first index in the Collection where a value satisfies the provided predicate function. Otherwise -1 is returned.
method findLastIndex
findLastIndex: ( predicate: (value: T, index: number, iter: this) => boolean, context?: unknown) => number;
Returns the last index in the Collection where a value satisfies the provided predicate function. Otherwise -1 is returned.
method flatMap
flatMap: <M>( mapper: (value: T, key: number, iter: this) => Iterable<M>, context?: unknown) => Indexed<M>;
Flat-maps the Collection, returning a Collection of the same type.
Similar to
collection.map(...).flatten(true)
.
method fromEntrySeq
fromEntrySeq: () => Seq.Keyed<unknown, unknown>;
If this is a collection of [key, value] entry tuples, it will return a Seq.Keyed of those entries.
method get
get: { <NSV>(index: number, notSetValue: NSV): T | NSV; (index: number): T };
Returns the value associated with the provided index, or notSetValue if the index is beyond the bounds of the Collection.
index
may be a negative number, which indexes back from the end of the Collection.s.get(-1)
gets the last item in the Collection.
method indexOf
indexOf: (searchValue: T) => number;
Returns the first index at which a given value can be found in the Collection, or -1 if it is not present.
method interleave
interleave: (...collections: Collection<unknown, T>[]) => this;
Returns a Collection of the same type with the provided
collections
interleaved into this collection.The resulting Collection includes the first item from each, then the second from each, etc.
<!-- runkit:activate { "preamble": "require('immutable')"} -->
const { List } = require('immutable')List([ 1, 2, 3 ]).interleave(List([ 'A', 'B', 'C' ]))// List [ 1, "A", 2, "B", 3, "C" ]The shortest Collection stops interleave.
<!-- runkit:activate { "preamble": "const { List } = require('immutable')" } -->
List([ 1, 2, 3 ]).interleave(List([ 'A', 'B' ]),List([ 'X', 'Y', 'Z' ]))// List [ 1, "A", "X", 2, "B", "Y" ]Since
interleave()
re-indexes values, it produces a complete copy, which hasO(N)
complexity.Note:
interleave
*cannot* be used inwithMutations
.
method interpose
interpose: (separator: T) => this;
Returns a Collection of the same type with
separator
between each item in this Collection.
method lastIndexOf
lastIndexOf: (searchValue: T) => number;
Returns the last index at which a given value can be found in the Collection, or -1 if it is not present.
method map
map: <M>( mapper: (value: T, key: number, iter: this) => M, context?: unknown) => Indexed<M>;
Returns a new Collection.Indexed with values passed through a
mapper
function.const { Collection } = require('immutable')Collection.Indexed([1,2]).map(x => 10 * x)// Seq [ 1, 2 ]Note:
map()
always returns a new instance, even if it produced the same value at every step.
method partition
partition: { <F extends T, C>( predicate: (this: C, value: T, index: number, iter: this) => value is F, context?: C ): [Indexed<T>, Indexed<F>]; <C>( predicate: (this: C, value: T, index: number, iter: this) => unknown, context?: C ): [this, this];};
Returns a new indexed Collection with the values for which the
predicate
function returns false and another for which is returns true.
method splice
splice: (index: number, removeNum: number, ...values: Array<T>) => this;
Splice returns a new indexed Collection by replacing a region of this Collection with new values. If values are not provided, it only skips the region to be removed.
index
may be a negative number, which indexes back from the end of the Collection.s.splice(-2)
splices after the second to last item.<!-- runkit:activate -->
const { List } = require('immutable')List([ 'a', 'b', 'c', 'd' ]).splice(1, 2, 'q', 'r', 's')// List [ "a", "q", "r", "s", "d" ]Since
splice()
re-indexes values, it produces a complete copy, which hasO(N)
complexity.Note:
splice
*cannot* be used inwithMutations
.
method toArray
toArray: () => Array<T>;
Shallowly converts this collection to an Array.
method toJS
toJS: () => Array<DeepCopy<T>>;
Deeply converts this Indexed collection to equivalent native JavaScript Array.
method toJSON
toJSON: () => Array<T>;
Shallowly converts this Indexed collection to equivalent native JavaScript Array.
method toSeq
toSeq: () => Seq.Indexed<T>;
Returns Seq.Indexed.
Modifiers
@override
method zip
zip: { <U>(other: Collection<unknown, U>): Indexed<[T, U]>; <U, V>( other: Collection<unknown, U>, other2: Collection<unknown, V> ): Indexed<[T, U, V]>; (...collections: Collection<unknown, unknown>[]): Indexed<unknown>;};
Returns a Collection of the same type "zipped" with the provided collections.
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>): Indexed<[T, U]>; <U, V>( other: Collection<unknown, U>, other2: Collection<unknown, V> ): Indexed<[T, U, V]>; (...collections: Collection<unknown, unknown>[]): Indexed<unknown>;};
Returns a Collection "zipped" with the provided collections.
Unlike
zip
,zipAll
continues zipping until the longest collection is exhausted. Missing values from shorter collections are filled withundefined
.const a = List([ 1, 2 ]);const b = List([ 3, 4, 5 ]);const c = a.zipAll(b); // List [ [ 1, 3 ], [ 2, 4 ], [ undefined, 5 ] ]
method zipWith
zipWith: { <U, Z>( zipper: (value: T, otherValue: U) => Z, otherCollection: Collection<unknown, U> ): Indexed<Z>; <U, V, Z>( zipper: (value: T, otherValue: U, thirdValue: V) => Z, otherCollection: Collection<unknown, U>, thirdCollection: Collection<unknown, V> ): Indexed<Z>; <Z>( zipper: (...values: unknown[]) => Z, ...collections: Collection<unknown, unknown>[] ): Indexed<Z>;};
Returns a Collection of the same type "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 Keyed
interface Keyed<K, V> extends Collection<K, V> {}
method [Symbol.iterator]
[Symbol.iterator]: () => IterableIterator<[K, V]>;
method concat
concat: { <KC, VC>(...collections: Array<Iterable<[KC, VC]>>): Keyed<K | KC, V | VC>; <C>(...collections: { [key: string]: C }[]): Keyed<string | K, V | C>;};
Returns a new Collection with other collections concatenated to this one.
method filter
filter: { <F extends V>( predicate: (value: V, key: K, iter: this) => value is F, context?: unknown ): Keyed<K, F>; ( predicate: (value: V, key: K, iter: this) => unknown, context?: unknown ): this;};
Returns a new Collection 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: <KM, VM>( mapper: (value: V, key: K, iter: this) => Iterable<[KM, VM]>, context?: unknown) => Keyed<KM, VM>;
Flat-maps the Collection, returning a Collection of the same type.
Similar to
collection.map(...).flatten(true)
.
method flip
flip: () => Keyed<V, K>;
Returns a new Collection.Keyed of the same type where the keys and values have been flipped.
<!-- runkit:activate -->
const { Map } = require('immutable')Map({ a: 'z', b: 'y' }).flip()// Map { "z": "a", "y": "b" }
method map
map: <M>( mapper: (value: V, key: K, iter: this) => M, context?: unknown) => Keyed<K, M>;
Returns a new Collection.Keyed with values passed through a
mapper
function.const { Collection } = require('immutable')Collection.Keyed({ 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.
method mapEntries
mapEntries: <KM, VM>( mapper: (entry: [K, V], index: number, iter: this) => [KM, VM] | undefined, context?: unknown) => Keyed<KM, VM>;
Returns a new Collection.Keyed of the same type with entries ([key, value] tuples) passed through a
mapper
function.<!-- runkit:activate -->
const { Map } = require('immutable')Map({ a: 1, b: 2 }).mapEntries(([ k, v ]) => [ k.toUpperCase(), v * 2 ])// Map { "A": 2, "B": 4 }Note:
mapEntries()
always returns a new instance, even if it produced the same entry at every step.If the mapper function returns
undefined
, then the entry will be filtered
method mapKeys
mapKeys: <M>( mapper: (key: K, value: V, iter: this) => M, context?: unknown) => Keyed<M, V>;
Returns a new Collection.Keyed of the same type with keys passed through a
mapper
function.<!-- runkit:activate -->
const { Map } = require('immutable')Map({ a: 1, b: 2 }).mapKeys(x => x.toUpperCase())// Map { "A": 1, "B": 2 }Note:
mapKeys()
always returns a new instance, even if it produced the same key at every step.
method partition
partition: { <F extends V, C>( predicate: (this: C, value: V, key: K, iter: this) => value is F, context?: C ): [Keyed<K, V>, Keyed<K, F>]; <C>( predicate: (this: C, value: V, key: K, iter: this) => unknown, context?: C ): [this, this];};
Returns a new keyed Collection with the values for which the
predicate
function returns false and another for which is returns true.
method toArray
toArray: () => Array<[K, V]>;
Shallowly converts this collection to an Array.
method toJS
toJS: () => { [x: string]: DeepCopy<V>; [x: number]: DeepCopy<V>; [x: symbol]: DeepCopy<V>;};
Deeply converts this Keyed collection to equivalent native JavaScript Object.
Converts keys to Strings.
method toJSON
toJSON: () => { [x: string]: V; [x: number]: V; [x: symbol]: V };
Shallowly converts this Keyed collection to equivalent native JavaScript Object.
Converts keys to Strings.
method toSeq
toSeq: () => Seq.Keyed<K, V>;
Returns Seq.Keyed.
Modifiers
@override
interface Set
interface Set<T> extends Collection<T, T> {}
method [Symbol.iterator]
[Symbol.iterator]: () => IterableIterator<T>;
method concat
concat: <U>(...collections: Array<Iterable<U>>) => Set<T | U>;
Returns a new Collection with other collections concatenated to this one.
method filter
filter: { <F extends T>( predicate: (value: T, key: T, iter: this) => value is F, context?: unknown ): Set<F>; ( predicate: (value: T, key: T, iter: this) => unknown, context?: unknown ): this;};
Returns a new Collection 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: T, iter: this) => Iterable<M>, context?: unknown) => Set<M>;
Flat-maps the Collection, returning a Collection of the same type.
Similar to
collection.map(...).flatten(true)
.
method map
map: <M>( mapper: (value: T, key: T, iter: this) => M, context?: unknown) => Set<M>;
Returns a new Collection.Set with values passed through a
mapper
function.Collection.Set([ 1, 2 ]).map(x => 10 * x)// Seq { 1, 2 }Note:
map()
always returns a new instance, even if it produced the same value at every step.
method partition
partition: { <F extends T, C>( predicate: (this: C, value: T, key: T, iter: this) => value is F, context?: C ): [Set<T>, Set<F>]; <C>( predicate: (this: C, value: T, key: T, iter: this) => unknown, context?: C ): [this, this];};
Returns a new set Collection with the values for which the
predicate
function returns false and another for which is returns true.
method toArray
toArray: () => Array<T>;
Shallowly converts this collection to an Array.
method toJS
toJS: () => Array<DeepCopy<T>>;
Deeply converts this Set collection to equivalent native JavaScript Array.
method toJSON
toJSON: () => Array<T>;
Shallowly converts this Set collection to equivalent native JavaScript Array.
method toSeq
toSeq: () => Seq.Set<T>;
Returns Seq.Set.
Modifiers
@override
namespace Collection.Indexed
namespace Collection.Indexed {}
Indexed Collections have incrementing numeric keys. They exhibit slightly different behavior than
Collection.Keyed
for some methods in order to better mirror the behavior of JavaScript'sArray
, and add methods which do not make sense on non-indexed Collections such asindexOf
.Unlike JavaScript arrays,
Collection.Indexed
s are always dense. "Unset" indices andundefined
indices are indistinguishable, and all indices from 0 tosize
are visited when iterated.All Collection.Indexed methods return re-indexed Collections. In other words, indices always start at 0 and increment until size. If you wish to preserve indices, using them as keys, convert to a Collection.Keyed by calling
toKeyedSeq
.
namespace Collection.Keyed
namespace Collection.Keyed {}
Keyed Collections have discrete keys tied to each value.
When iterating
Collection.Keyed
, each iteration will yield a[K, V]
tuple, in other words,Collection#entries
is the default iterator for Keyed Collections.
namespace Collection.Set
namespace Collection.Set {}
Set Collections only represent values. They have no associated keys or indices. Duplicate values are possible in the lazy
Seq.Set
s, however the concreteSet
Collection does not allow duplicate values.Collection methods on Collection.Set such as
map
andforEach
will provide the value as both the first and second arguments to the provided function.const { Collection } = require('immutable')const seq = Collection.Set([ 'A', 'B', 'C' ])// Seq { "A", "B", "C" }seq.forEach((v, k) =>assert.equal(v, k))
namespace List
namespace List {}
Lists are ordered indexed dense collections, much like a JavaScript Array.
Lists are immutable and fully persistent with O(log32 N) gets and sets, and O(1) push and pop.
Lists implement Deque, with efficient addition and removal from both the end (
push
,pop
) and beginning (unshift
,shift
).Unlike a JavaScript Array, there is no distinction between an "unset" index and an index set to
undefined
.List#forEach
visits all indices from 0 to size, regardless of whether they were explicitly defined.
function isList
isList: (maybeList: unknown) => maybeList is List<unknown>;
True if the provided value is a List
<!-- runkit:activate -->
const { List } = require('immutable');List.isList([]); // falseList.isList(List()); // true
function of
of: <T>(...values: Array<T>) => List<T>;
Creates a new List containing
values
.<!-- runkit:activate -->
const { List } = require('immutable');List.of(1, 2, 3, 4)// List [ 1, 2, 3, 4 ]Note: Values are not altered or converted in any way.
<!-- runkit:activate -->
const { List } = require('immutable');List.of({x:1}, 2, [3], 4)// List [ { x: 1 }, 2, [ 3 ], 4 ]
namespace Map
namespace Map {}
Immutable Map is an unordered Collection.Keyed of (key, value) pairs with
O(log32 N)
gets andO(log32 N)
persistent sets.Iteration order of a Map is undefined, however is stable. Multiple iterations of the same Map will iterate in the same order.
Map's keys can be of any type, and use
Immutable.is
to determine key equality. This allows the use of any value (including NaN) as a key.Because
Immutable.is
returns equality based on value semantics, and Immutable collections are treated as values, any Immutable collection may be used as a key.<!-- runkit:activate -->
const { Map, List } = require('immutable');Map().set(List([ 1 ]), 'listofone').get(List([ 1 ]));// 'listofone'Any JavaScript object may be used as a key, however strict identity is used to evaluate key equality. Two similar looking objects will represent two different keys.
Implemented by a hash-array mapped trie.
function isMap
isMap: (maybeMap: unknown) => maybeMap is Map<unknown, unknown>;
True if the provided value is a Map
<!-- runkit:activate -->
const { Map } = require('immutable')Map.isMap({}) // falseMap.isMap(Map()) // true
namespace OrderedMap
namespace OrderedMap {}
A type of Map that has the additional guarantee that the iteration order of entries will be the order in which they were set().
The iteration behavior of OrderedMap is the same as native ES6 Map and JavaScript Object.
Note that
OrderedMap
are more expensive than non-orderedMap
and may consume more memory.OrderedMap#set
is amortized O(log32 N), but not stable.
function isOrderedMap
isOrderedMap: ( maybeOrderedMap: unknown) => maybeOrderedMap is OrderedMap<unknown, unknown>;
True if the provided value is an OrderedMap.
namespace OrderedSet
namespace OrderedSet {}
A type of Set that has the additional guarantee that the iteration order of values will be the order in which they were
add
ed.The iteration behavior of OrderedSet is the same as native ES6 Set.
Note that
OrderedSet
are more expensive than non-orderedSet
and may consume more memory.OrderedSet#add
is amortized O(log32 N), but not stable.
function fromKeys
fromKeys: { <T>(iter: Collection.Keyed<T, unknown>): OrderedSet<T>; <T>(iter: Collection<T, unknown>): OrderedSet<T>; (obj: { [key: string]: unknown }): OrderedSet<string>;};
OrderedSet.fromKeys()
creates a new immutable OrderedSet containing the keys from this Collection or JavaScript Object.
function isOrderedSet
isOrderedSet: ( maybeOrderedSet: unknown) => maybeOrderedSet is OrderedSet<unknown>;
True if the provided value is an OrderedSet.
function of
of: <T>(...values: Array<T>) => OrderedSet<T>;
Creates a new OrderedSet containing
values
.
namespace Record
namespace Record {}
A record is similar to a JS object, but enforces a specific set of allowed string keys, and has default values.
The
Record()
function produces new Record Factories, which when called create Record instances.const { Record } = require('immutable')const ABRecord = Record({ a: 1, b: 2 })const myRecord = ABRecord({ b: 3 })Records always have a value for the keys they define.
remove
ing a key from a record simply resets it to the default value for that key.myRecord.get('a') // 1myRecord.get('b') // 3const myRecordWithoutB = myRecord.remove('b')myRecordWithoutB.get('b') // 2Values provided to the constructor not found in the Record type will be ignored. For example, in this case, ABRecord is provided a key "x" even though only "a" and "b" have been defined. The value for "x" will be ignored for this record.
const myRecord = ABRecord({ b: 3, x: 10 })myRecord.get('x') // undefinedBecause Records have a known set of string keys, property get access works as expected, however property sets will throw an Error.
Note: IE8 does not support property access. Only use
get()
when supporting IE8.myRecord.b // 3myRecord.b = 5 // throws ErrorRecord Types can be extended as well, allowing for custom methods on your Record. This is not a common pattern in functional environments, but is in many JS programs.
However Record Types are more restricted than typical JavaScript classes. They do not use a class constructor, which also means they cannot use class properties (since those are technically part of a constructor).
While Record Types can be syntactically created with the JavaScript
class
form, the resulting Record function is actually a factory function, not a class constructor. Even though Record Types are not classes, JavaScript currently requires the use ofnew
when creating new Record instances if they are defined as aclass
.class ABRecord extends Record({ a: 1, b: 2 }) {getAB() {return this.a + this.b;}}var myRecord = new ABRecord({b: 3})myRecord.getAB() // 4**Flow Typing Records:**
Immutable.js exports two Flow types designed to make it easier to use Records with flow typed code,
RecordOf<TProps>
andRecordFactory<TProps>
.When defining a new kind of Record factory function, use a flow type that describes the values the record contains along with
RecordFactory<TProps>
. To type instances of the Record (which the factory function returns), useRecordOf<TProps>
.Typically, new Record definitions will export both the Record factory function as well as the Record instance type for use in other code.
import type { RecordFactory, RecordOf } from 'immutable';// Use RecordFactory<TProps> for defining new Record factory functions.type Point3DProps = { x: number, y: number, z: number };const defaultValues: Point3DProps = { x: 0, y: 0, z: 0 };const makePoint3D: RecordFactory<Point3DProps> = Record(defaultValues);export makePoint3D;// Use RecordOf<T> for defining new instances of that Record.export type Point3D = RecordOf<Point3DProps>;const some3DPoint: Point3D = makePoint3D({ x: 10, y: 20, z: 30 });**Flow Typing Record Subclasses:**
Records can be subclassed as a means to add additional methods to Record instances. This is generally discouraged in favor of a more functional API, since Subclasses have some minor overhead. However the ability to create a rich API on Record types can be quite valuable.
When using Flow to type Subclasses, do not use
RecordFactory<TProps>
, instead apply the props type when subclassing:type PersonProps = {name: string, age: number};const defaultValues: PersonProps = {name: 'Aristotle', age: 2400};const PersonRecord = Record(defaultValues);class Person extends PersonRecord<PersonProps> {getName(): string {return this.get('name')}setName(name: string): this {return this.set('name', name);}}**Choosing Records vs plain JavaScript objects**
Records offer a persistently immutable alternative to plain JavaScript objects, however they're not required to be used within Immutable.js collections. In fact, the deep-access and deep-updating functions like
getIn()
andsetIn()
work with plain JavaScript Objects as well.Deciding to use Records or Objects in your application should be informed by the tradeoffs and relative benefits of each:
- *Runtime immutability*: plain JS objects may be carefully treated as immutable, however Record instances will *throw* if attempted to be mutated directly. Records provide this additional guarantee, however at some marginal runtime cost. While JS objects are mutable by nature, the use of type-checking tools like [Flow](https://medium.com/@gcanti/immutability-with-flow-faa050a1aef4) can help gain confidence in code written to favor immutability.
- *Value equality*: Records use value equality when compared with
is()
orrecord.equals()
. That is, two Records with the same keys and values are equal. Plain objects use *reference equality*. Two objects with the same keys and values are not equal since they are different objects. This is important to consider when using objects as keys in aMap
or values in aSet
, which use equality when retrieving values.- *API methods*: Records have a full featured API, with methods like
.getIn()
, and.equals()
. These can make working with these values easier, but comes at the cost of not allowing keys with those names.- *Default values*: Records provide default values for every key, which can be useful when constructing Records with often unchanging values. However default values can make using Flow and TypeScript more laborious.
- *Serialization*: Records use a custom internal representation to efficiently store and update their values. Converting to and from this form isn't free. If converting Records to plain objects is common, consider sticking with plain objects to begin with.
function Factory
Factory: <TProps extends object>( values?: Partial<TProps> | Iterable<[string, unknown]>) => Record<TProps> & Readonly<TProps>;
function getDescriptiveName
getDescriptiveName: (record: Record<any>) => string;
Records allow passing a second parameter to supply a descriptive name that appears when converting a Record to a string or in any error messages. A descriptive name for any record can be accessed by using this method. If one was not provided, the string "Record" is returned.
const { Record } = require('immutable')const Person = Record({name: null}, 'Person')var me = Person({ name: 'My Name' })me.toString() // "Person { "name": "My Name" }"Record.getDescriptiveName(me) // "Person"
function isRecord
isRecord: (maybeRecord: unknown) => maybeRecord is Record<{}>;
True if
maybeRecord
is an instance of a Record.
interface Factory
interface Factory<TProps extends object> {}
property displayName
displayName: string;
The name provided to
Record(values, name)
can be accessed withdisplayName
.
construct signature
new (values?: Partial<TProps> | Iterable<[string, unknown]>): Record<TProps> & Readonly<TProps>;
call signature
(values?: Partial<TProps> | Iterable<[string, unknown]>): Record<TProps> & Readonly<TProps>;
namespace Record.Factory
namespace Record.Factory {}
A Record.Factory is created by the
Record()
function. Record instances are created by passing it some of the accepted values for that Record type:<!-- runkit:activate { "preamble": "const { Record } = require('immutable')" } -->
// makePerson is a Record Factory functionconst makePerson = Record({ name: null, favoriteColor: 'unknown' });// alan is a Record instanceconst alan = makePerson({ name: 'Alan' });Note that Record Factories return
Record<TProps> & Readonly<TProps>
, this allows use of both the Record instance API, and direct property access on the resulting instances:<!-- runkit:activate { "preamble": "const { Record } = require('immutable');const makePerson = Record({ name: null, favoriteColor: 'unknown' });const alan = makePerson({ name: 'Alan' });" } -->
// Use the Record APIconsole.log('Record API: ' + alan.get('name'))// Or direct property access (Readonly)console.log('property access: ' + alan.name)**Flow Typing Records:**
Use the
RecordFactory<TProps>
Flow type to get high quality type checking of Records:import type { RecordFactory, RecordOf } from 'immutable';// Use RecordFactory<TProps> for defining new Record factory functions.type PersonProps = { name: ?string, favoriteColor: string };const makePerson: RecordFactory<PersonProps> = Record({ name: null, favoriteColor: 'unknown' });// Use RecordOf<T> for defining new instances of that Record.type Person = RecordOf<PersonProps>;const alan: Person = makePerson({ name: 'Alan' });
namespace Seq
namespace Seq {}
Seq
describes a lazy operation, allowing them to efficiently chain use of all the higher-order collection methods (such asmap
andfilter
) by not creating intermediate collections.**Seq is immutable** — Once a Seq is created, it cannot be changed, appended to, rearranged or otherwise modified. Instead, any mutative method called on a
Seq
will return a newSeq
.**Seq is lazy** —
Seq
does as little work as necessary to respond to any method call. Values are often created during iteration, including implicit iteration when reducing or converting to a concrete data structure such as aList
or JavaScriptArray
.For example, the following performs no work, because the resulting
Seq
's values are never iterated:const { Seq } = require('immutable')const oddSquares = Seq([ 1, 2, 3, 4, 5, 6, 7, 8 ]).filter(x => x % 2 !== 0).map(x => x * x)Once the
Seq
is used, it performs only the work necessary. In this example, no intermediate arrays are ever created, filter is called three times, and map is only called once:oddSquares.get(1); // 9Any collection can be converted to a lazy Seq with
Seq()
.<!-- runkit:activate -->
const { Map } = require('immutable')const map = Map({ a: 1, b: 2, c: 3 })const lazySeq = Seq(map)Seq
allows for the efficient chaining of operations, allowing for the expression of logic that can otherwise be very tedious:lazySeq.flip().map(key => key.toUpperCase()).flip()// Seq { A: 1, B: 1, C: 1 }As well as expressing logic that would otherwise seem memory or time limited, for example
Range
is a special kind of Lazy sequence.<!-- runkit:activate -->
const { Range } = require('immutable')Range(1, Infinity).skip(1000).map(n => -n).filter(n => n % 2 === 0).take(2).reduce((r, n) => r * n, 1)// 1006008Seq is often used to provide a rich collection API to JavaScript Object.
Seq({ x: 0, y: 1, z: 2 }).map(v => v * 2).toObject();// { x: 0, y: 2, z: 4 }
function Indexed
Indexed: typeof Indexed;
Always returns Seq.Indexed, discarding associated keys and supplying incrementing indices.
Note:
Seq.Indexed
is a conversion function and not a class, and does not use thenew
keyword during construction.
function isSeq
isSeq: ( maybeSeq: unknown) => maybeSeq is Indexed<unknown> | Keyed<unknown, unknown> | Set<unknown>;
True if
maybeSeq
is a Seq, it is not backed by a concrete structure such as Map, List, or Set.
function Keyed
Keyed: { <K, V>(collection?: Iterable<[K, V]>): Keyed<K, V>; <V>(obj: { [key: string]: V }): Keyed<string, V>;};
Always returns a Seq.Keyed, if input is not keyed, expects an collection of [K, V] tuples.
Note:
Seq.Keyed
is a conversion function and not a class, and does not use thenew
keyword during construction.
function Set
Set: typeof Set;
Always returns a Seq.Set, discarding associated indices or keys.
Note:
Seq.Set
is a conversion function and not a class, and does not use thenew
keyword during construction.
interface Indexed
interface Indexed<T> extends Seq<number, T>, Collection.Indexed<T> {}
method [Symbol.iterator]
[Symbol.iterator]: () => IterableIterator<T>;
method concat
concat: <C>(...valuesOrCollections: Array<Iterable<C> | C>) => Indexed<T | C>;
Returns a new Seq with other collections concatenated to this one.
method filter
filter: { <F extends T>( predicate: (value: T, index: number, iter: this) => value is F, context?: unknown ): Indexed<F>; ( predicate: (value: T, index: number, iter: this) => unknown, context?: unknown ): this;};
Returns a new Seq 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) => Indexed<M>;
Flat-maps the Seq, returning a a Seq of the same type.
Similar to
seq.map(...).flatten(true)
.
method map
map: <M>( mapper: (value: T, key: number, iter: this) => M, context?: unknown) => Indexed<M>;
Returns a new Seq.Indexed with values passed through a
mapper
function.const { Seq } = require('immutable')Seq.Indexed([ 1, 2 ]).map(x => 10 * x)// Seq [ 10, 20 ]Note:
map()
always returns a new instance, even if it produced the same value at every step.
method partition
partition: { <F extends T, C>( predicate: (this: C, value: T, index: number, iter: this) => value is F, context?: C ): [Indexed<T>, Indexed<F>]; <C>( predicate: (this: C, value: T, index: number, iter: this) => unknown, context?: C ): [this, this];};
Returns a new indexed Seq with the values for which the
predicate
function returns false and another for which is returns true.
method toArray
toArray: () => Array<T>;
Shallowly converts this collection to an Array.
method toJS
toJS: () => Array<DeepCopy<T>>;
Deeply converts this Indexed Seq to equivalent native JavaScript Array.
method toJSON
toJSON: () => Array<T>;
Shallowly converts this Indexed Seq to equivalent native JavaScript Array.
method toSeq
toSeq: () => this;
Returns itself
method zip
zip: { <U>(other: Collection<unknown, U>): Indexed<[T, U]>; <U, V>( other: Collection<unknown, U>, other2: Collection<unknown, V> ): Indexed<[T, U, V]>; (...collections: Collection<unknown, unknown>[]): Indexed<unknown>;};
Returns a Seq "zipped" with the provided collections.
Like
zipWith
, but using the defaultzipper
: creating anArray
.const a = Seq([ 1, 2, 3 ]);const b = Seq([ 4, 5, 6 ]);const c = a.zip(b); // Seq [ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ]
method zipAll
zipAll: { <U>(other: Collection<unknown, U>): Indexed<[T, U]>; <U, V>( other: Collection<unknown, U>, other2: Collection<unknown, V> ): Indexed<[T, U, V]>; (...collections: Collection<unknown, unknown>[]): Indexed<unknown>;};
Returns a Seq "zipped" with the provided collections.
Unlike
zip
,zipAll
continues zipping until the longest collection is exhausted. Missing values from shorter collections are filled withundefined
.const a = Seq([ 1, 2 ]);const b = Seq([ 3, 4, 5 ]);const c = a.zipAll(b); // Seq [ [ 1, 3 ], [ 2, 4 ], [ undefined, 5 ] ]
method zipWith
zipWith: { <U, Z>( zipper: (value: T, otherValue: U) => Z, otherCollection: Collection<unknown, U> ): Indexed<Z>; <U, V, Z>( zipper: (value: T, otherValue: U, thirdValue: V) => Z, otherCollection: Collection<unknown, U>, thirdCollection: Collection<unknown, V> ): Indexed<Z>; <Z>( zipper: (...values: unknown[]) => Z, ...collections: Collection<unknown, unknown>[] ): Indexed<Z>;};
Returns a Seq "zipped" with the provided collections by using a custom
zipper
function.const a = Seq([ 1, 2, 3 ]);const b = Seq([ 4, 5, 6 ]);const c = a.zipWith((a, b) => a + b, b);// Seq [ 5, 7, 9 ]
interface Keyed
interface Keyed<K, V> extends Seq<K, V>, Collection.Keyed<K, V> {}
method [Symbol.iterator]
[Symbol.iterator]: () => IterableIterator<[K, V]>;
method concat
concat: { <KC, VC>(...collections: Array<Iterable<[KC, VC]>>): Keyed<K | KC, V | VC>; <C>(...collections: { [key: string]: C }[]): Keyed<string | K, V | C>;};
Returns a new Seq with other collections concatenated to this one.
All entries will be present in the resulting Seq, even if they have the same key.
method filter
filter: { <F extends V>( predicate: (value: V, key: K, iter: this) => value is F, context?: unknown ): Keyed<K, F>; ( predicate: (value: V, key: K, iter: this) => unknown, context?: unknown ): this;};
Returns a new Seq 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) => Keyed<KM, VM>;
Flat-maps the Seq, returning a Seq of the same type.
Similar to
seq.map(...).flatten(true)
.
method flip
flip: () => Keyed<V, K>;
See Also
Collection.Keyed.flip
method map
map: <M>( mapper: (value: V, key: K, iter: this) => M, context?: unknown) => Keyed<K, M>;
Returns a new Seq.Keyed with values passed through a
mapper
function.const { Seq } = require('immutable')Seq.Keyed({ 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.
method mapEntries
mapEntries: <KM, VM>( mapper: (entry: [K, V], index: number, iter: this) => [KM, VM] | undefined, context?: unknown) => Keyed<KM, VM>;
See Also
Collection.Keyed.mapEntries
method mapKeys
mapKeys: <M>( mapper: (key: K, value: V, iter: this) => M, context?: unknown) => Keyed<M, V>;
See Also
Collection.Keyed.mapKeys
method partition
partition: { <F extends V, C>( predicate: (this: C, value: V, key: K, iter: this) => value is F, context?: C ): [Keyed<K, V>, Keyed<K, F>]; <C>( predicate: (this: C, value: V, key: K, iter: this) => unknown, context?: C ): [this, this];};
Returns a new keyed Seq with the values for which the
predicate
function returns false and another for which is returns true.
method toArray
toArray: () => Array<[K, V]>;
Shallowly converts this collection to an Array.
method toJS
toJS: () => { [x: string]: DeepCopy<V>; [x: number]: DeepCopy<V>; [x: symbol]: DeepCopy<V>;};
Deeply converts this Keyed Seq to equivalent native JavaScript Object.
Converts keys to Strings.
method toJSON
toJSON: () => { [x: string]: V; [x: number]: V; [x: symbol]: V };
Shallowly converts this Keyed Seq to equivalent native JavaScript Object.
Converts keys to Strings.
method toSeq
toSeq: () => this;
Returns itself
interface Set
interface Set<T> extends Seq<T, T>, Collection.Set<T> {}
method [Symbol.iterator]
[Symbol.iterator]: () => IterableIterator<T>;
method concat
concat: <U>(...collections: Array<Iterable<U>>) => Set<T | U>;
Returns a new Seq with other collections concatenated to this one.
All entries will be present in the resulting Seq, even if they are duplicates.
method filter
filter: { <F extends T>( predicate: (value: T, key: T, iter: this) => value is F, context?: unknown ): Set<F>; ( predicate: (value: T, key: T, iter: this) => unknown, context?: unknown ): this;};
Returns a new Seq 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: T, iter: this) => Iterable<M>, context?: unknown) => Set<M>;
Flat-maps the Seq, returning a Seq of the same type.
Similar to
seq.map(...).flatten(true)
.
method map
map: <M>( mapper: (value: T, key: T, iter: this) => M, context?: unknown) => Set<M>;
Returns a new Seq.Set with values passed through a
mapper
function.Seq.Set([ 1, 2 ]).map(x => 10 * x)// Seq { 10, 20 }Note:
map()
always returns a new instance, even if it produced the same value at every step.
method partition
partition: { <F extends T, C>( predicate: (this: C, value: T, key: T, iter: this) => value is F, context?: C ): [Set<T>, Set<F>]; <C>( predicate: (this: C, value: T, key: T, iter: this) => unknown, context?: C ): [this, this];};
Returns a new set Seq with the values for which the
predicate
function returns false and another for which is returns true.
method toArray
toArray: () => Array<T>;
Shallowly converts this collection to an Array.
method toJS
toJS: () => Array<DeepCopy<T>>;
Deeply converts this Set Seq to equivalent native JavaScript Array.
method toJSON
toJSON: () => Array<T>;
Shallowly converts this Set Seq to equivalent native JavaScript Array.
method toSeq
toSeq: () => this;
Returns itself
namespace Seq.Indexed
namespace Seq.Indexed {}
Seq
which represents an ordered indexed list of values.
function of
of: <T>(...values: Array<T>) => Indexed<T>;
Provides an Seq.Indexed of the values provided.
namespace Seq.Keyed
namespace Seq.Keyed {}
Seq
which represents key-value pairs.
namespace Seq.Set
namespace Seq.Set {}
Seq
which represents a set of values.Because
Seq
are often lazy,Seq.Set
does not provide the same guarantee of value uniqueness as the concreteSet
.
function of
of: <T>(...values: Array<T>) => Set<T>;
Returns a Seq.Set of the provided values
namespace Set
namespace Set {}
A Collection of unique values with
O(log32 N)
adds and has.When iterating a Set, the entries will be (value, value) pairs. Iteration order of a Set is undefined, however is stable. Multiple iterations of the same Set will iterate in the same order.
Set values, like Map keys, may be of any type. Equality is determined using
Immutable.is
, enabling Sets to uniquely include other Immutable collections, custom value types, and NaN.
function fromKeys
fromKeys: { <T>(iter: Collection.Keyed<T, unknown>): Set<T>; <T>(iter: Collection<T, unknown>): Set<T>; (obj: { [key: string]: unknown }): Set<string>;};
Set.fromKeys()
creates a new immutable Set containing the keys from this Collection or JavaScript Object.
function intersect
intersect: <T>(sets: Iterable<Iterable<T>>) => Set<T>;
Set.intersect()
creates a new immutable Set that is the intersection of a collection of other sets.const { Set } = require('immutable')const intersected = Set.intersect([Set([ 'a', 'b', 'c' ])Set([ 'c', 'a', 't' ])])// Set [ "a", "c" ]
function isSet
isSet: (maybeSet: unknown) => maybeSet is Set<unknown>;
True if the provided value is a Set
function of
of: <T>(...values: Array<T>) => Set<T>;
Creates a new Set containing
values
.
function union
union: <T>(sets: Iterable<Iterable<T>>) => Set<T>;
Set.union()
creates a new immutable Set that is the union of a collection of other sets.const { Set } = require('immutable')const unioned = Set.union([Set([ 'a', 'b', 'c' ])Set([ 'c', 'a', 't' ])])// Set [ "a", "b", "c", "t" ]
namespace Stack
namespace Stack {}
Stacks are indexed collections which support very efficient O(1) addition and removal from the front using
unshift(v)
andshift()
.For familiarity, Stack also provides
push(v)
,pop()
, andpeek()
, but be aware that they also operate on the front of the list, unlike List or a JavaScript Array.Note:
reverse()
or any inherent reverse traversal (reduceRight
,lastIndexOf
, etc.) is not efficient with a Stack.Stack is implemented with a Single-Linked List.
Package Files (1)
Dependencies (0)
No dependencies.
Dev Dependencies (0)
No dev dependencies.
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/immutable
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/immutable)
- HTML<a href="https://www.jsdocs.io/package/immutable"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 10573 ms. - Missing or incorrect documentation? Open an issue for this package.