immutable
- Version 5.1.4
- Published
- 709 kB
- No dependencies
- MIT license
Install
npm i immutableyarn add immutablepnpm add immutableOverview
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:
Collectionis a conversion function and not a class, and does not use thenewkeyword 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.
fromJSwill 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
reviveris 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"". Thisreviveris expected to return a new Immutable Collection, allowing for custom conversions from deep JS objects. Finally, apathis provided which is the sequence of keys to this value from the starting value.reviveracts similarly to the [same parameter inJSON.parse][1].If
reviveris not provided, the default behavior will convert Objects into Maps and Arrays into Lists like so:Accordingly, this example converts native JS data to OrderedMap and List:
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.
Property 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: number]: V; [key: symbol]: V }, key: string ): V; <V, NSV>( collection: { [key: string]: V; [key: number]: V; [key: symbol]: 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].
function getIn
getIn: { <C, P extends readonly PropertyKey[]>(object: C, keyPath: [...P]): RetrievePath< C, P >; <C, P extends KeyPath<unknown>>(object: C, keyPath: P): unknown; <C, P extends readonly PropertyKey[], NSV>( collection: C, keyPath: [...P], notSetValue: NSV ): RetrievePath<C, P> extends never ? NSV : RetrievePath<C, P>; <C, P extends KeyPath<unknown>, NSV>( object: C, keyPath: P, notSetValue: NSV ): 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.
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).
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: string | boolean | number, keyPath: KeyPath<unknown>): never; <K>(collection: unknown, keyPath: KeyPath<K>): 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.
function is
is: (first: unknown, second: unknown) => boolean;Value equality check with semantics similar to
Object.is, but treats ImmutableCollections as values, equal if the secondCollectionincludes equivalent values.It's used throughout Immutable when checking for equality, including
Mapkey equality andSetmembership.is()compares primitive types like strings and numbers, Immutable.js collections likeMapandList, but also any custom object which implementsValueObjectby providingequals()andhashCode()methods.Note: Unlike
Object.is,Immutable.isassumes0and-0are 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
maybeAssociativeis either a Keyed or Indexed Collection.
function isCollection
isCollection: ( maybeCollection: unknown) => maybeCollection is Collection<unknown, unknown>;True if
maybeCollectionis a Collection, or any of its subclasses.
function isImmutable
isImmutable: ( maybeImmutable: unknown) => maybeImmutable is Collection<unknown, unknown>;True if
maybeImmutableis an Immutable Collection or Record.Note: Still returns true even if the collections is within a
withMutations().
function isIndexed
isIndexed: ( maybeIndexed: unknown) => maybeIndexed is Collection.Indexed<unknown>;True if
maybeIndexedis a Collection.Indexed, or any of its subclasses.
function isKeyed
isKeyed: ( maybeKeyed: unknown) => maybeKeyed is Collection.Keyed<unknown, unknown>;True if
maybeKeyedis a Collection.Keyed, or any of its subclasses.
function isList
isList: (maybeList: unknown) => maybeList is List<unknown>;True if
maybeListis a List.
function isMap
isMap: (maybeMap: unknown) => maybeMap is Map<unknown, unknown>;True if
maybeMapis a Map.Also true for OrderedMaps.
function isOrdered
isOrdered: { <T>(maybeOrdered: Iterable<T>): maybeOrdered is OrderedCollection<T>; (maybeOrdered: unknown): maybeOrdered is OrderedCollection<unknown>;};True if
maybeOrderedis a Collection where iteration order is well defined. True for Collection.Indexed as well as OrderedMap and OrderedSet.
function isOrderedMap
isOrderedMap: ( maybeOrderedMap: unknown) => maybeOrderedMap is OrderedMap<unknown, unknown>;True if
maybeOrderedMapis an OrderedMap.
function isOrderedSet
isOrderedSet: ( maybeOrderedSet: unknown) => maybeOrderedSet is OrderedSet<unknown>;True if
maybeOrderedSetis an OrderedSet.
function isRecord
isRecord: (maybeRecord: unknown) => maybeRecord is Record<object>;True if
maybeRecordis a Record.
function isSeq
isSeq: ( maybeSeq: unknown) => maybeSeq is | Seq.Indexed<unknown> | Seq.Keyed<unknown, unknown> | Seq.Set<unknown>;True if
maybeSeqis a Seq.
function isSet
isSet: (maybeSet: unknown) => maybeSet is Set<unknown>;True if
maybeSetis a Set.Also true for OrderedSets.
function isStack
isStack: (maybeStack: unknown) => maybeStack is Stack<unknown>;True if
maybeStackis a Stack.
function isValueObject
isValueObject: (maybeValue: unknown) => maybeValue is ValueObject;True if
maybeValueis 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 aMapor members in aSet.
function List
List: typeof List;Create a new immutable List containing the values of the provided collection-like.
Note:
Listis a factory function and not a class, and does not use thenewkeyword during construction.
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:
Mapis a factory function and not a class, and does not use thenewkeyword during construction.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.
Property 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.
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.,Maps,Records, and objects), indexed (e.g.,Lists and arrays), or set-like (e.g.,Sets). If they fall into separate categories,mergeDeepwill 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.
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 themergerfunction 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.
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
mergerfunction whenever an existing value is encountered.A functional alternative to
collection.mergeWith()which will also work with plain Objects and Arrays.
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:
OrderedMapis a factory function and not a class, and does not use thenewkeyword during construction.
function OrderedSet
OrderedSet: typeof OrderedSet;Create a new immutable OrderedSet containing the values of the provided collection-like.
Note:
OrderedSetis a factory function and not a class, and does not use thenewkeyword 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, wherestartdefaults to 0,stepto 1, andendto infinity. Whenstartis equal toend, returns empty range.Note:
Rangeis a factory function and not a class, and does not use thenewkeyword during construction.import { Range } from 'immutable'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:
Recordis a factory function and not a class, and does not use thenewkeyword 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].
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.
function Repeat
Repeat: <T>(value: T, times?: number) => Seq.Indexed<T>;Returns a Seq.Indexed of
valuerepeatedtimestimes. Whentimesis not defined, returns an infiniteSeqofvalue.Note:
Repeatis a factory function and not a class, and does not use thenewkeyword during construction.import { Repeat } from '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
Seqbased on the input.* If a
Seq, that sameSeq. * If anCollection, aSeqof 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:
Seqis a conversion function and not a class, and does not use thenewkeyword 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.
function Set
Set: typeof Set;Create a new immutable Set containing the values of the provided collection-like.
Note:
Setis a factory function and not a class, and does not use thenewkeyword 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.
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:
Stackis a factory function and not a class, and does not use thenewkeyword 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]).
function updateIn
updateIn: { <K extends PropertyKey, V, C extends Collection<K, V>>( collection: C, keyPath: KeyPath<K>, updater: ( value: RetrievePath<C, Array<K>> | undefined ) => unknown | undefined ): C; <K extends PropertyKey, V, C extends Collection<K, V>, NSV>( collection: C, keyPath: KeyPath<K>, notSetValue: NSV, updater: ( value: NSV | RetrievePathReducer<C, never, never[], GetNativeType<C>> ) => unknown ): C; <TProps extends object, C extends Record<TProps>, K extends keyof TProps>( record: C, keyPath: KeyPath<K>, updater: ( value: RetrievePathReducer<C, never, never[], GetNativeType<C>> ) => unknown ): C; <TProps extends object, C extends Record<TProps>, K extends keyof TProps, NSV>( record: C, keyPath: KeyPath<K>, notSetValue: NSV, updater: ( value: NSV | RetrievePathReducer<C, never, never[], GetNativeType<C>> ) => unknown ): C; <K extends PropertyKey, V, C extends V[]>( collection: V[], keyPath: KeyPath<string | number>, updater: ( value: RetrievePathReducer<C, never, never[], GetNativeType<C>> ) => unknown ): V[]; <K extends PropertyKey, V, C extends V[], NSV>( collection: V[], keyPath: KeyPath<K>, notSetValue: NSV, updater: ( value: NSV | RetrievePathReducer<C, never, never[], GetNativeType<C>> ) => unknown ): V[]; <K extends PropertyKey, C>( object: C, keyPath: KeyPath<K>, updater: ( value: RetrievePathReducer<C, never, never[], GetNativeType<C>> ) => unknown ): C; <K extends PropertyKey, C, NSV>( object: C, keyPath: KeyPath<K>, notSetValue: NSV, updater: ( value: NSV | RetrievePathReducer<C, never, never[], GetNativeType<C>> ) => unknown ): C; < K extends PropertyKey, V, C extends { [key: string]: V; [key: number]: V; [key: symbol]: V } >( collection: C, keyPath: KeyPath<K>, updater: ( value: RetrievePathReducer<C, never, never[], GetNativeType<C>> ) => unknown ): { [key: string]: V; [key: number]: V; [key: symbol]: V }; < K extends PropertyKey, V, C extends { [key: string]: V; [key: number]: V; [key: symbol]: V }, NSV >( collection: C, keyPath: KeyPath<K>, notSetValue: NSV, updater: ( value: NSV | RetrievePathReducer<C, never, never[], GetNativeType<C>> ) => unknown ): { [key: string]: V; [key: number]: V; [key: symbol]: V };};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.
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
Seqif necessary.If
predicateis provided, then this returns the count of entries in the Collection for which thepredicatereturns true.
method countBy
countBy: <G>( grouper: (value: V, key: K, iter: this) => G, context?: unknown) => Map<G, number>;Returns a
Seq.Keyedof counts, grouped by the return value of thegrouperfunction.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
entrySeqinstead, 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
predicatereturns 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
predicatefunction returns true.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
predicatefunction returns false.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
predicatereturns 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
predicatereturns true.
method findKey
findKey: ( predicate: (value: V, key: K, iter: this) => boolean, context?: unknown) => K | undefined;Returns the key for which the
predicatereturns 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
predicatereturns true.Note:
predicatewill 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
predicatereturns true.Note:
predicatewill 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
predicatereturns true.Note:
predicatewill be called for each entry in reverse.
method first
first: { <NSV>(notSetValue: NSV): V | NSV; (): V };In case the
Collectionis not empty returns the first element of theCollection. In case theCollectionis 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
depthcan 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
sideEffectis executed for every entry in the Collection.Unlike
Array#forEach, if any call ofsideEffectreturnsfalse, 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
undefinedvalue, so ifnotSetValueis 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.
Plain JavaScript Object or Arrays may be nested within an Immutable.js Collection, and getIn() can access those values as well:
method groupBy
groupBy: <G>( grouper: (value: V, key: K, iter: this) => G, context?: unknown) => Map<G, this>;Returns a
MapofCollection, grouped by the return value of thegrouperfunction.Note: This is always an eager operation.
method has
has: (key: K) => boolean;True if a key exists within this
Collection, usingImmutable.isto determine equality
method hashCode
hashCode: () => number;Computes and returns the hashed identity for this Collection.
The
hashCodeof a Collection is used to determine potential equality, and is used when adding this to aSetor as a key in aMap, enabling lookup via a different instance.If two values have the same
hashCode, they are [not guaranteed to be equal][Hash Collision]. If two values have differenthashCodes, 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.isto determine equality contains
method isEmpty
isEmpty: () => boolean;Returns true if this Collection includes no values.
For some lazy
Seq,isEmptymight need to iterate to determine emptiness. At most one iteration will occur.
method isSubset
isSubset: (iter: Iterable<V>) => boolean;True if
iterincludes 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
keySeqinstead, 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
Collectionis not empty returns the last element of theCollection. In case theCollectionis 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
mapperfunction.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
comparatoris 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,
maxwill 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
comparatorreturns 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 acomparatorValueMapperwhich allows for comparing by more sophisticated means:
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
comparatoris 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,
minwill 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
comparatorreturns 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 acomparatorValueMapperwhich allows for comparing by more sophisticated means:
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
predicatefunction 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
reducerfor every entry in the Collection and passing along the reduced value.If
initialReductionis 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
amountentries from this Collection.
method skipLast
skipLast: (amount: number) => this;Returns a new Collection of the same type which excludes the last
amountentries 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
predicatefirst returns true.
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
predicatefirst returns false.
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
predicatereturns 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
comparatoris not provided, a default comparator uses<and>.comparator(valueA, valueB):* Returns
0if the elements should not be swapped. * Returns-1(or any negative number) ifvalueAcomes beforevalueB* Returns1(or any positive number) ifvalueAcomes aftervalueB* Alternatively, can return a value of thePairSortingenum 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.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 acomparatorValueMapperwhich allows for sorting by more sophisticated means: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
amountentries from this Collection.
method takeLast
takeLast: (amount: number) => this;Returns a new Collection of the same type which includes the last
amountentries 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
predicatereturns false.
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
predicatereturns true.
method toArray
toArray: () => Array<V> | Array<[K, V]>;Shallowly converts this collection to an Array.
Collection.Indexed, andCollection.Setproduce an Array of values.Collection.Keyedproduce 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.SetbecomeArray, whileCollection.KeyedbecomeObject, 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.SetbecomeArray, whileCollection.KeyedbecomeObject, 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.
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 onMapor other keyed collections,collection.toList()discards the keys and creates a list of only the values, whereasList(collection)creates a list of entry tuples.
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:
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
valueSeqinstead, 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.
Note:
clearcan 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:
concatcan be used inwithMutations.merge
method delete
delete: (index: number) => List<T>;Returns a new List which excludes this
indexand with a size 1 less than this List. Values at indices aboveindexare shifted down by 1 to fill the position.This is synonymous with
list.splice(index, 1).indexmay be a negative number, which indexes back from the end of the List.v.delete(-1)deletes the last item in the List.Note:
deletecannot be safely used in IE8Since
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 inkeyPathdo not exist, no change will occur.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.
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
predicatefunction 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
valueatindexwith a size 1 more than this List. Values at indices aboveindexare shifted over by 1.This is synonymous with
list.splice(index, 0, value).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
mapperfunction.
method merge
merge: <C>(...collections: Array<Iterable<C>>) => List<T | C>;method mergeDeepIn
mergeDeepIn: ( keyPath: Iterable<unknown>, ...collections: Array<unknown>) => this;Note:
mergeDeepIncan be used inwithMutations.See Also
Map#mergeDeepIn
method mergeIn
mergeIn: (keyPath: Iterable<unknown>, ...collections: Array<unknown>) => this;Note:
mergeIncan 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
predicatefunction 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#popbecause 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:
popcan be used inwithMutations.
method push
push: (...values: Array<T>) => List<T>;Returns a new List with the provided
valuesappended, starting at this List'ssize.Note:
pushcan 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
valueatindex. Ifindexalready exists in this List, it will be replaced.indexmay 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
indexlarger thansize, the returned List'ssizewill be large enough to include theindex.Note:
setcan be used inwithMutations.
method setIn
setIn: (keyPath: Iterable<unknown>, value: unknown) => this;Returns a new List having set
valueat thiskeyPath. If any keys inkeyPathdo 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.
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.
Note:
setIncan be used inwithMutations.
method setSize
setSize: (size: number) => List<T>;Returns a new List with size
size. Ifsizeis less than this List's size, the new List will exclude values at the higher indices. Ifsizeis 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,
setSizeused in conjunction withwithMutationsmay 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#shiftbecause it returns a new List rather than the removed value. Usefirst()to get the first value in this List.Note:
shiftcan be used inwithMutations.
method shuffle
shuffle: (random?: () => number) => this;Returns a new List with its values shuffled thanks to the [Fisher–Yates](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) algorithm. It uses Math.random, but you can provide your own random number generator.
method unshift
unshift: (...values: Array<T>) => List<T>;Returns a new List with the provided
valuesprepended, shifting other values ahead to higher indices.Note:
unshiftcan 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
indexwith the return value of callingupdaterwith the existing value, ornotSetValueifindexwas not set. If called with a single argument,updateris called with the List itself.indexmay be a negative number, which indexes back from the end of the List.v.update(-1)updates the last item in the List.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:
Note:
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:
updateIncan 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.
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,zipAllcontinues zipping until the longest collection is exhausted. Missing values from shorter collections are filled withundefined.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
zipperfunction.
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
withMutationsto 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
withMutationsto 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,
asMutablereturns 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.
Note:
clearcan 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:
deletecannot be safely used in IE8, but is provided to mirror the ES6 collection API.Note:
deletecan be used inwithMutations.remove
method deleteAll
deleteAll: (keys: Iterable<K>) => this;Returns a new Map which excludes the provided
keys.Note:
deleteAllcan 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 inkeyPathdo not exist, no change will occur.Note:
deleteIncan 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
predicatefunction 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
mapperfunction.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
mergeare shallowly converted before being merged. No nested values are altered. ```Note:
mergecan 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.,Maps,Records, and objects), indexed (e.g.,Lists and arrays), or set-like (e.g.,Sets). If they fall into separate categories,mergeDeepwill 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.Note:
mergeDeepcan be used inwithMutations.
method mergeDeepIn
mergeDeepIn: ( keyPath: Iterable<unknown>, ...collections: Array<unknown>) => this;A combination of
updateInandmergeDeep, 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:
mergeDeepIncan 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 themergerfunction to determine the resulting value. Collections are considered incompatible if they fall into separate categories between keyed, indexed, and set-like.Note:
mergeDeepWithcan be used inwithMutations.
method mergeIn
mergeIn: (keyPath: Iterable<unknown>, ...collections: Array<unknown>) => this;A combination of
updateInandmerge, 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:
mergeIncan 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 themergerfunction for dealing with conflicts.Note:
mergeWithcan 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
predicatefunction 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.
Note:
setcan be used inwithMutations.
method setIn
setIn: (keyPath: Iterable<unknown>, value: unknown) => this;Returns a new Map having set
valueat thiskeyPath. If any keys inkeyPathdo not exist, a new immutable Map will be created at that key.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.
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:
setIncan 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
comparatoris not provided, a default comparator uses<and>.comparator(valueA, valueB):* Returns
0if the elements should not be swapped. * Returns-1(or any negative number) ifvalueAcomes beforevalueB* Returns1(or any positive number) ifvalueAcomes aftervalueB* Alternatively, can return a value of thePairSortingenum type * Is pure, i.e. it must always return the same value for the same pair of values.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 acomparatorValueMapperwhich allows for sorting by more sophisticated means: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
keywith the return value of callingupdaterwith the existing value.Similar to:
map.set(key, updater(map.get(key))).This is most commonly used to call methods on collections within a structure of data. For example, in order to
.push()onto a nestedList,updateandpushcan be used together:When a
notSetValueis provided, it is provided to theupdaterfunction when the value at the key does not exist in the Map.However, if the
updaterfunction returns the same value it was called with, then no change will occur. This is still true ifnotSetValueis provided.For code using ES2015 or later, using
notSetValueis 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:
If no key is provided, then the
updaterfunction return value is returned as well.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
Note:
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
updaterto 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,updateInandpushcan be used together:If any keys in
keyPathdo not exist, new ImmutableMaps will be created at those keys. If thekeyPathdoes not already contain a value, theupdaterfunction will be called withnotSetValue, if provided, otherwiseundefined.If the
updaterfunction returns the same value it was called with, then no change will occur. This is still true ifnotSetValueis provided.For code using ES2015 or later, using
notSetValueis 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:
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.
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:
updateIncan 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 likemergeare done.As an example, this results in the creation of 2, not 4, new Maps:
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 PropertyKey]: 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: unknown, 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
undefinedvalue, so ifnotSetValueis not provided and this method returnsundefined, that does not guarantee the key was not found.
method getIn
getIn: <P extends readonly PropertyKey[]>( 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 OrderedCollection
interface OrderedCollection<T> {}Interface representing all oredered collections. This includes
List,Stack,Map,OrderedMap,Set, andOrderedSet. return ofisOrdered()return true in that case.
method [Symbol.iterator]
[Symbol.iterator]: () => IterableIterator<T>;method toArray
toArray: () => Array<T>;Shallowly converts this collection to an Array.
interface OrderedMap
interface OrderedMap<K, V> extends Map<K, V>, OrderedCollection<[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
predicatefunction 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
mapperfunction.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
mergeare shallowly converted before being merged. No nested values are altered.Note:
mergecan 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
predicatefunction 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.
Note:
setcan be used inwithMutations.
interface OrderedSet
interface OrderedSet<T> extends Set<T>, OrderedCollection<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
predicatefunction 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
mapperfunction.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
predicatefunction 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
collectionsthat does not already exist in this OrderedSet.Note:
unioncan 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,zipAllcontinues 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
zipperfunction.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! Onlysetmay 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 originalSeqwhilefilter()does not.Note:
Range,RepeatandSeqs made fromArrays andObjects 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
joiniterates the Seq of three values.var squares = Seq([ 1, 2, 3 ]).map(x => x * x) squares.join() + squares.join()
If you know a
Seqwill 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 concat
concat: (...valuesOrCollections: Array<unknown>) => Seq<unknown, unknown>;Returns a new Sequence of the same type with other values and collection-like 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 ): 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
predicatefunction 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
mapperfunction.import { Seq } from '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
mapperfunction.import { Seq } from '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
predicatefunction 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:
addcan 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:
clearcan 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:
deletecan be used inwithMutations.Note:
delete**cannot** be safely used in IE8, useremoveif 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
predicatefunction 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:
intersectcan 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
mapperfunction.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
predicatefunction 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
comparatoris not provided, a default comparator uses<and>.comparator(valueA, valueB):* Returns
0if the elements should not be swapped. * Returns-1(or any negative number) ifvalueAcomes beforevalueB* Returns1(or any positive number) ifvalueAcomes aftervalueB* Alternatively, can return a value of thePairSortingenum type * Is pure, i.e. it must always return the same value for the same pair of values.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 acomparatorValueMapperwhich allows for sorting by more sophisticated means: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.Note:
subtractcan be used inwithMutations.
method union
union: <C>(...collections: Array<Iterable<C>>) => Set<T | C>;Returns a Set including any value from
collectionsthat does not already exist in this Set.Note:
unioncan 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:
clearcan 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
predicatefunction 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
mapperfunction.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#shiftand is not equivalent toList#pop.
method push
push: (...values: Array<T>) => Stack<T>;Alias for
Stack#unshiftand 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#shiftbecause it returns a new Stack rather than the removed value. Usefirst()orpeek()to get the first value in this Stack.Note:
shiftcan be used inwithMutations.
method unshift
unshift: (...values: Array<T>) => Stack<T>;Returns a new Stack with the provided
valuesprepended, shifting other values ahead to higher indices.This is very efficient for Stack.
Note:
unshiftcan be used inwithMutations.
method unshiftAll
unshiftAll: (iter: Iterable<T>) => Stack<T>;Like
Stack#unshift, but accepts a collection rather than varargs.Note:
unshiftAllcan 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,zipAllcontinues 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
zipperfunction.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
hashCodeof a Collection is used to determine potential equality, and is used when adding this to aSetor as a key in aMap, enabling lookup via a different instance.Note: hashCode() MUST return a Uint32 number. The easiest way to guarantee this is to return
myHash | 0from a custom implementation.If two values have the same
hashCode, they are [not guaranteed to be equal][Hash Collision]. If two values have differenthashCodes, 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 = -1member RightThenLeft
RightThenLeft = +1Type 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 PropertyKey ? 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
unknownon object instead of recursive call as we have a circular reference issue
type FromJS
type FromJS<JSValue> = JSValue extends FromJSNoTransform ? JSValue : JSValue extends Array<unknown> ? FromJSArray<JSValue> : JSValue extends object ? FromJSObject<JSValue> : unknown;type FromJSArray
type FromJSArray<JSValue> = JSValue extends Array<infer T> ? List<FromJS<T>> : never;type FromJSNoTransform
type FromJSNoTransform = | Collection<unknown, unknown> | number | string | null | undefined;type FromJSObject
type FromJSObject<JSValue> = JSValue extends object ? Map<keyof JSValue, FromJS<JSValue[keyof JSValue]>> : never;type GetNativeType
type GetNativeType<S> = S extends MapOf<infer T> ? T : S extends List<infer I> ? Array<I> : S;Convert an immutable type to the equivalent plain TS type - MapOf -> object - List -> Array
type Head
type Head<T extends ReadonlyArray<unknown>> = T extends [infer H, ...Array<unknown>] ? H : never;type KeyPath
type KeyPath<K> = OrderedCollection<K> | ArrayLike<K>;KeyPath allowed for
xxxInmethods
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<unknown>> = P extends [] ? P : RetrievePathReducer<R, Head<P>, Tail<P>>;type RetrievePathReducer
type RetrievePathReducer< T, C, L extends ReadonlyArray<unknown>, NT = GetNativeType<T>> = // we can not retrieve a path from a primitive type T extends string | number | boolean | null | undefined ? never : C extends keyof NT ? L extends [] // L extends [] means we are at the end of the path, lets return the current type ? NT[C] : // we are not at the end of the path, lets continue with the next key RetrievePathReducer<NT[C], Head<L>, Tail<L>> : // C is not a "key" of NT, so the path is invalid never;type Tail
type Tail<T extends ReadonlyArray<unknown>> = T extends [unknown, ...infer I] ? I : Array<never>;Namespaces
namespace Collection
namespace Collection {}The
Collectionis 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 asmapandfilter).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
MapandSet.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.Indexedis a conversion function and not a class, and does not use thenewkeyword 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.Keyedis a conversion function and not a class, and does not use thenewkeyword during construction.
function Set
Set: <T>(collection?: Iterable<T> | ArrayLike<T>) => Set<T>;Similar to
Collection(), but always returns a Collection.Set.Note:
Collection.Setis a factory function and not a class, and does not use thenewkeyword during construction.
interface Indexed
interface Indexed<T> extends Collection<number, T>, OrderedCollection<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
predicatefunction 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.
indexmay 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
collectionsinterleaved into this collection.The resulting Collection includes the first item from each, then the second from each, etc.
The shortest Collection stops interleave.
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
separatorbetween 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
mapperfunction.import { Collection } from '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
predicatefunction 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.
indexmay be a negative number, which indexes back from the end of the Collection.s.splice(-2)splices after the second to last item.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.
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,zipAllcontinues 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
zipperfunction.
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
predicatefunction 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.
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
mapperfunction.import { Collection } from '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
mapperfunction.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
mapperfunction.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
predicatefunction 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
predicatefunction 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
mapperfunction.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
predicatefunction 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.Keyedfor 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.Indexeds are always dense. "Unset" indices andundefinedindices are indistinguishable, and all indices from 0 tosizeare 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#entriesis 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.Sets, however the concreteSetCollection does not allow duplicate values.Collection methods on Collection.Set such as
mapandforEachwill provide the value as both the first and second arguments to the provided function.import { Collection } from '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#forEachvisits all indices from 0 to size, regardless of whether they were explicitly defined.
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.isto determine key equality. This allows the use of any value (including NaN) as a key.Because
Immutable.isreturns equality based on value semantics, and Immutable collections are treated as values, any Immutable collection may be used as a key.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
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
OrderedMapare more expensive than non-orderedMapand may consume more memory.OrderedMap#setis 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
added.The iteration behavior of OrderedSet is the same as native ES6 Set.
Note that
OrderedSetare more expensive than non-orderedSetand may consume more memory.OrderedSet#addis 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.import { Record } from 'immutable'const ABRecord = Record({ a: 1, b: 2 })const myRecord = ABRecord({ b: 3 })Records always have a value for the keys they define.
removeing 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
classform, 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 ofnewwhen 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 aMapor 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]>) => RecordOf<TProps>;function getDescriptiveName
getDescriptiveName: <TProps extends object>(record: RecordOf<TProps>) => 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.
import { Record } from '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<object>;True if
maybeRecordis 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]>): RecordOf<TProps>;call signature
(values?: Partial<TProps> | Iterable<[string, unknown]>): RecordOf<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: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:
namespace Seq
namespace Seq {}Seqdescribes a lazy operation, allowing them to efficiently chain use of all the higher-order collection methods (such asmapandfilter) 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
Seqwill return a newSeq.**Seq is lazy** —
Seqdoes 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 aListor JavaScriptArray.For example, the following performs no work, because the resulting
Seq's values are never iterated:import { Seq } from 'immutable'const oddSquares = Seq([ 1, 2, 3, 4, 5, 6, 7, 8 ]).filter(x => x % 2 !== 0).map(x => x * x)Once the
Seqis 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().Seqallows 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
Rangeis a special kind of Lazy sequence.Seq 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.Indexedis a conversion function and not a class, and does not use thenewkeyword during construction.
function isSeq
isSeq: ( maybeSeq: unknown) => maybeSeq is Indexed<unknown> | Keyed<unknown, unknown> | Set<unknown>;True if
maybeSeqis 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.Keyedis a conversion function and not a class, and does not use thenewkeyword during construction.
function Set
Set: typeof Set;Always returns a Seq.Set, discarding associated indices or keys.
Note:
Seq.Setis a conversion function and not a class, and does not use thenewkeyword 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
predicatefunction 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
mapperfunction.import { Seq } from '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
predicatefunction 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,zipAllcontinues 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
zipperfunction.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
predicatefunction 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
mapperfunction.import { Seq } from '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
predicatefunction 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
predicatefunction 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
mapperfunction.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
predicatefunction 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 {}Seqwhich 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 {}Seqwhich represents key-value pairs.
namespace Seq.Set
namespace Seq.Set {}Seqwhich represents a set of values.Because
Seqare often lazy,Seq.Setdoes 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.import { Set } from '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.import { Set } from '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[](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 13032 ms. - Missing or incorrect documentation? Open an issue for this package.
