Back to Immutable Js

Collection.Indexed

website/docs/Collection.Indexed.mdx

5.1.524.3 KB
Original Source

import Repl from '@/repl/Repl.tsx'; import CodeLink from '@/mdx-components/CodeLink.tsx';

Collection.Indexed

Indexed Collections have incrementing numeric keys. They exhibit slightly different behavior than Collection.Keyed for some methods in order to better mirror the behavior of JavaScript's Array, and add methods which do not make sense on non-indexed Collections such as indexOf.

Unlike JavaScript arrays, Collection.Indexeds are always dense. "Unset" indices and undefined indices are indistinguishable, and all indices from 0 to size are visited when iterated.

All Collection.Indexed methods return re-indexed Collections. In other words, indices always start at 0 and increment until size. If you wish to preserve indices, using them as keys, convert to a Collection.Keyed by calling toKeyedSeq.

Construction

<MemberLabel label="Collection.Indexed()" />

Creates a new Collection.Indexed.

<Signature code={function Collection.Indexed<T>(collection?: Iterable<T> | ArrayLike<T>): Collection.Indexed<T>;} />

Note: Collection.Indexed is a conversion function and not a class, and does not use the new keyword during construction.

Reading values

<MemberLabel label="get()" />

Returns the value associated with the provided index, or notSetValue if the index is beyond the bounds of the Collection.

<Signature code={get<NSV>(index: number, notSetValue: NSV): T | NSV; get(index: number): T | undefined;} />

index may be a negative number, which indexes back from the end of the Collection. s.get(-1) gets the last item in the Collection.

<MemberLabel label="has()" />

True if a key exists within this Collection, using Immutable.is to determine equality.

<Signature code={has(key: number): boolean;} />

<MemberLabel label="includes()" alias="contains()" />

True if a value exists within this Collection, using Immutable.is to determine equality.

<Signature code={includes(value: T): boolean;} />

<MemberLabel label="first()" />

In case the Collection is not empty returns the first element of the Collection. In case the Collection is empty returns the optional default value if provided, if no default value is provided returns undefined.

<Signature code={first<NSV>(notSetValue: NSV): T | NSV; first(): T | undefined;} />

<MemberLabel label="last()" />

In case the Collection is not empty returns the last element of the Collection. In case the Collection is empty returns the optional default value if provided, if no default value is provided returns undefined.

<Signature code={last<NSV>(notSetValue: NSV): T | NSV; last(): T | undefined;} />

Conversion to JavaScript types

<MemberLabel label="toJS()" />

Deeply converts this Indexed collection to equivalent native JavaScript Array.

<Signature code={toJS(): Array<DeepCopy<T>>;} />

<MemberLabel label="toJSON()" />

Shallowly converts this Indexed collection to equivalent native JavaScript Array.

<Signature code={toJSON(): Array<T>;} />

<MemberLabel label="toArray()" />

Shallowly converts this collection to an Array.

<Signature code={toArray(): Array<T>;} />

<MemberLabel label="toObject()" />

Shallowly converts this Collection to an Object.

<Signature code={toObject(): { [key: string]: T };} />

Converts keys to Strings.

Conversion to Seq

<MemberLabel label="toSeq()" />

Returns Seq.Indexed.

<Signature code={toSeq(): Seq.Indexed<T>;} />

<MemberLabel label="fromEntrySeq()" />

If this is a collection of [key, value] entry tuples, it will return a Seq.Keyed of those entries.

<Signature code={fromEntrySeq(): Seq.Keyed<unknown, unknown>;} />

<MemberLabel label="toKeyedSeq()" />

Returns a Seq.Keyed with the same key-value entries as this Collection.Indexed.

<Signature code={toKeyedSeq(): Seq.Keyed<number, T>;} />

<MemberLabel label="toIndexedSeq()" />

Returns a Seq.Indexed with the same values as this Collection.Indexed.

<Signature code={toIndexedSeq(): Seq.Indexed<T>;} />

<MemberLabel label="toSetSeq()" />

Returns a Seq.Set with the same values as this Collection.Indexed.

<Signature code={toSetSeq(): Seq.Set<T>;} />

Combination

<MemberLabel label="interpose()" />

Returns a Collection of the same type with separator between each item in this Collection.

<Signature code={interpose(separator: T): this;} />

<MemberLabel label="interleave()" />

Returns a Collection of the same type with the provided collections interleaved into this collection.

<Signature code={interleave(...collections: Array<Collection<unknown, T>>): this;} />

The resulting Collection includes the first item from each, then the second from each, etc.

<Repl defaultValue={Collection.Indexed([1, 2, 3]).interleave(List(['A', 'B', 'C']));} />

The shortest Collection stops interleave.

<Repl defaultValue={Collection.Indexed([1, 2, 3]).interleave(List(['A', 'B']), List(['X', 'Y', 'Z']));} />

Since interleave() re-indexes values, it produces a complete copy, which has O(N) complexity.

Note: interleave cannot be used in withMutations.

<MemberLabel label="splice()" />

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.

<Signature code={splice(index: number, removeNum: number, ...values: Array<T>): this;} />

index may be a negative number, which indexes back from the end of the Collection. s.splice(-2) splices after the second to last item.

<Repl defaultValue={Collection.Indexed(['a', 'b', 'c', 'd']).splice(1, 2, 'q', 'r', 's');} />

Since splice() re-indexes values, it produces a complete copy, which has O(N) complexity.

Note: splice cannot be used in withMutations.

<MemberLabel label="zip()" />

Returns a Collection of the same type "zipped" with the provided collections.

<Signature code={zip<U>(other: Collection<unknown, U>): Collection.Indexed<[T, U]>;} /> <Signature code={zip<U, V>(other: Collection<unknown, U>, other2: Collection<unknown, V>): Collection.Indexed<[T, U, V]>;} /> <Signature code={zip(...collections: Array<Collection<unknown, unknown>>): Collection.Indexed<unknown>;} />

Like zipWith, but using the default zipper: creating an Array.

<Repl defaultValue={const a = Collection.Indexed([1, 2, 3]); const b = Collection.Indexed([4, 5, 6]); a.zip(b);} />

<MemberLabel label="zipAll()" />

Returns a Collection "zipped" with the provided collections. Unlike zip, zipAll continues zipping until the longest collection is exhausted. Missing values from shorter collections are filled with undefined.

<Signature code={zipAll<U>(other: Collection<unknown, U>): Collection.Indexed<[T, U]>;} /> <Signature code={zipAll<U, V>(other: Collection<unknown, U>, other2: Collection<unknown, V>): Collection.Indexed<[T, U, V]>;} /> <Signature code={zipAll(...collections: Array<Collection<unknown, unknown>>): Collection.Indexed<unknown>;} />

<Repl defaultValue={const a = Collection.Indexed([1, 2]); const b = Collection.Indexed([3, 4, 5]); a.zipAll(b);} />

<MemberLabel label="zipWith()" />

Returns a Collection of the same type "zipped" with the provided collections by using a custom zipper function.

<Signature code={zipWith<U, Z>(zipper: (value: T, otherValue: U) => Z, otherCollection: Collection<unknown, U>): Collection.Indexed<Z>;} /> <Signature code={zipWith<U, V, Z>(zipper: (value: T, otherValue: U, thirdValue: V) => Z, otherCollection: Collection<unknown, U>, thirdCollection: Collection<unknown, V>): Collection.Indexed<Z>;} /> <Signature code={zipWith<Z>(zipper: (...values: Array<unknown>) => Z, ...collections: Array<Collection<unknown, unknown>>): Collection.Indexed<Z>;} />

<Repl defaultValue={const a = Collection.Indexed([1, 2, 3]); const b = Collection.Indexed([4, 5, 6]); a.zipWith((a, b) => a + b, b);} />

<MemberLabel label="flatten()" />

Flattens nested Collections.

<Signature code={flatten(depth?: number): Collection<unknown, unknown>;} /> <Signature code={flatten(shallow?: boolean): Collection<unknown, unknown>;} />

Will deeply flatten the Collection by default, returning a Collection of the same type, but a depth can be provided in the form of a number or boolean (where true means to shallowly flatten one level). A depth of 0 (or shallow: false) will deeply flatten.

Flattens only others Collection, not Arrays or Objects.

Note: flatten(true) operates on Collection<unknown, Collection<K, V>> and returns Collection<K, V>

Search for value

<MemberLabel label="indexOf()" />

Returns the first index at which a given value can be found in the Collection, or -1 if it is not present.

<Signature code={indexOf(searchValue: T): number;} />

<MemberLabel label="lastIndexOf()" />

Returns the last index at which a given value can be found in the Collection, or -1 if it is not present.

<Signature code={lastIndexOf(searchValue: T): number;} />

<MemberLabel label="findIndex()" />

Returns the first index in the Collection where a value satisfies the provided predicate function. Otherwise -1 is returned.

<Signature code={findIndex(predicate: (value: T, index: number, iter: this) => boolean, context?: unknown): number;} />

<MemberLabel label="findLastIndex()" />

Returns the last index in the Collection where a value satisfies the provided predicate function. Otherwise -1 is returned.

<Signature code={findLastIndex(predicate: (value: T, index: number, iter: this) => boolean, context?: unknown): number;} />

<MemberLabel label="find()" />

Returns the first value for which the predicate returns true.

<Signature code={find(predicate: (value: T, index: number, iter: this) => boolean, context?: unknown): T | undefined;} />

<MemberLabel label="findLast()" />

Returns the last value for which the predicate returns true.

<Signature code={findLast(predicate: (value: T, index: number, iter: this) => boolean, context?: unknown): T | undefined;} />

Note: predicate will be called for each entry in reverse.

<MemberLabel label="findEntry()" />

Returns the first [key, value] entry for which the predicate returns true.

<Signature code={findEntry(predicate: (value: T, index: number, iter: this) => boolean, context?: unknown): [number, T] | undefined;} />

<MemberLabel label="findLastEntry()" />

Returns the last [key, value] entry for which the predicate returns true.

<Signature code={findLastEntry(predicate: (value: T, index: number, iter: this) => boolean, context?: unknown): [number, T] | undefined;} />

<MemberLabel label="findKey()" />

Returns the key for which the predicate returns true.

<Signature code={findKey(predicate: (value: T, index: number, iter: this) => boolean, context?: unknown): number | undefined;} />

<MemberLabel label="findLastKey()" />

Returns the last key for which the predicate returns true.

<Signature code={findLastKey(predicate: (value: T, index: number, iter: this) => boolean, context?: unknown): number | undefined;} />

Note: predicate will be called for each entry in reverse.

<MemberLabel label="keyOf()" />

Returns the key associated with the search value, or undefined.

<Signature code={keyOf(searchValue: T): number;} />

<MemberLabel label="lastKeyOf()" />

Returns the last key associated with the search value, or undefined.

<Signature code={lastKeyOf(searchValue: T): number;} />

<MemberLabel label="max()" />

Returns the maximum value in this collection. If any values are comparatively equivalent, the first one found will be returned.

<Signature code={max(comparator?: Comparator<T>): T | undefined;} />

The comparator is used in the same way as Collection#sort. If it is not provided, the default comparator is >.

When two values are considered equivalent, the first encountered will be returned. Otherwise, max will operate independent of the order of input as long as the comparator is commutative. The default comparator > is commutative only when types do not differ.

If comparator returns 0 and either value is NaN, undefined, or null, that value will be returned.

<MemberLabel label="maxBy()" />

Like max, but also accepts a comparatorValueMapper which allows for comparing by more sophisticated means.

<Signature code={maxBy<C>(comparatorValueMapper: (value: T, key: number, iter: this) => C, comparator?: Comparator<C>): T | undefined;} />

<Repl defaultValue={const l = List([ { name: 'Bob', avgHit: 1 }, { name: 'Max', avgHit: 3 }, { name: 'Lili', avgHit: 2 } , ]); l.maxBy(i => i.avgHit);} />

<MemberLabel label="min()" />

Returns the minimum value in this collection. If any values are comparatively equivalent, the first one found will be returned.

<Signature code={min(comparator?: Comparator<T>): T | undefined;} />

The comparator is used in the same way as Collection#sort. If it is not provided, the default comparator is <.

When two values are considered equivalent, the first encountered will be returned. Otherwise, min will operate independent of the order of input as long as the comparator is commutative. The default comparator < is commutative only when types do not differ.

If comparator returns 0 and either value is NaN, undefined, or null, that value will be returned.

<MemberLabel label="minBy()" />

Like min, but also accepts a comparatorValueMapper which allows for comparing by more sophisticated means.

<Signature code={minBy<C>(comparatorValueMapper: (value: T, key: number, iter: this) => C, comparator?: Comparator<C>): T | undefined;} />

<Repl defaultValue={const l = List([ { name: 'Bob', avgHit: 1 }, { name: 'Max', avgHit: 3 }, { name: 'Lili', avgHit: 2 } , ]); l.minBy(i => i.avgHit);} />

Sequence algorithms

<MemberLabel label="concat()" />

Returns a new Collection with other collections concatenated to this one.

<Signature code={concat<C>(...valuesOrCollections: Array<Iterable<C> | C>): Collection.Indexed<T | C>;} />

<MemberLabel label="map()" />

Returns a new Collection.Indexed with values passed through a mapper function.

<Signature code={map<M>(mapper: (value: T, key: number, iter: this) => M, context?: unknown): Collection.Indexed<M>;} />

<Repl defaultValue={Collection.Indexed([1, 2]).map((x) => 10 * x)} />

Note: map() always returns a new instance, even if it produced the same value at every step.

<MemberLabel label="flatMap()" />

Flat-maps the Collection, returning a Collection of the same type.

<Signature code={flatMap<M>(mapper: (value: T, key: number, iter: this) => Iterable<M>, context?: unknown): Collection.Indexed<M>;} />

Similar to collection.map(...).flatten(true).

<MemberLabel label="filter()" />

Returns a new Collection with only the values for which the predicate function returns true.

<Signature code={filter<F extends T>(predicate: (value: T, index: number, iter: this) => value is F, context?: unknown): Collection.Indexed<F>;} /> <Signature code={filter(predicate: (value: T, index: number, iter: this) => unknown, context?: unknown): this;} />

Note: filter() always returns a new instance, even if it results in not filtering out any values.

<MemberLabel label="partition()" />

Returns a new indexed Collection with the values for which the predicate function returns false and another for which is returns true.

<Signature code={partition<F extends T, C>(predicate: (this: C, value: T, index: number, iter: this) => value is F, context?: C): [Collection.Indexed<T>, Collection.Indexed<F>];} /> <Signature code={partition<C>(predicate: (this: C, value: T, index: number, iter: this) => unknown, context?: C): [this, this];} />

<MemberLabel label="[Symbol.iterator]()" />

<Signature code={[Symbol.iterator](): IterableIterator<T>;} />

<MemberLabel label="filterNot()" />

Returns a new Collection with only the values for which the predicate function returns false.

<Signature code={filterNot(predicate: (value: T, index: number, iter: this) => unknown, context?: unknown): this;} />

<Repl defaultValue={Collection.Indexed([1, 2, 3]).filterNot((x) => x > 2)} />

Note: filterNot() always returns a new instance, even if it results in not filtering out any values.

<MemberLabel label="reverse()" />

Returns a new Collection with the values in reverse order.

<Signature code={reverse(): this;} />

<MemberLabel label="sort()" />

Returns a new sorted Collection, sorted by the natural order of the values.

<Signature code={sort(): Collection.Indexed<T>;} />

If a comparator is not provided, a default comparator uses < and >.

Note: sort() always returns a new instance, even if the original was already sorted.

Note: This is always an eager operation.

<MemberLabel label="sortBy()" />

Returns a new sorted Collection, sorted by the provided comparator function.

<Signature code={sortBy<R>(comparator: (value: T) => R): Collection.Indexed<T>;} />

Note: sortBy() always returns a new instance, even if the original was already sorted.

Note: This is always an eager operation.

<MemberLabel label="groupBy()" />

Groups the values by the return value of the mapper function, and returns a Collection.Indexed of Arrays of grouped values.

<Signature code={groupBy<K>(mapper: (value: T) => K): Collection.Indexed<Array<T>>;} />

Value equality

<MemberLabel label="equals()" />

Returns true if the Collections are of the same size and all values are equal.

<Signature code={equals(other: unknown): other is this;} />

<MemberLabel label="hashCode()" />

Returns a hash code for this Collection.

<Signature code={hashCode(): number;} />

Reading deep values

<MemberLabel label="getIn()" />

Returns the value at the given nested path, or notSetValue if any key in the path is not present.

<Signature code={getIn<NSV>(path: Array<string | number>, notSetValue: NSV): T | NSV;} /> <Signature code={getIn(path: Array<string | number>): T | undefined;} />

<MemberLabel label="hasIn()" />

Returns a boolean if the given nested path exists.

<Signature code={hasIn(path: Array<string | number>): boolean;} />

Persistent changes

<MemberLabel label="update()" />

Returns a new Collection.Indexed with the value at the given index updated to the new value.

<Signature code={update(index: number, updater: (value: T) => T): this;} />

Conversion to Collections

<MemberLabel label="toMap()" />

Converts this Collection.Indexed to a Map. The first value of each entry is used as the key.

<Signature code={toMap(): Collection.Keyed<T, T>;} />

<MemberLabel label="toOrderedMap()" />

Converts this Collection.Indexed to an OrderedMap. The first value of each entry is used as the key.

<Signature code={toOrderedMap(): Collection.OrderedKeyed<T, T>;} />

<MemberLabel label="toSet()" />

Converts this Collection.Indexed to a Set.

<Signature code={toSet(): Collection.Set<T>;} />

<MemberLabel label="toOrderedSet()" />

Converts this Collection.Indexed to an OrderedSet.

<Signature code={toOrderedSet(): Collection.OrderedSet<T>;} />

<MemberLabel label="toList()" />

Converts this Collection.Indexed to a List.

<Signature code={toList(): Collection.Indexed<T>;} />

<MemberLabel label="toStack()" />

Converts this Collection.Indexed to a Stack.

<Signature code={toStack(): Collection.Indexed<T>;} />

Iterators

<MemberLabel label="keys()" />

Returns an Iterable of the keys in the Collection.

<Signature code={keys(): Iterable<number>;} />

<MemberLabel label="values()" />

Returns an Iterable of the values in the Collection.

<Signature code={values(): Iterable<T>;} />

<MemberLabel label="entries()" />

Returns an Iterable of the [key, value] entries in the Collection.

<Signature code={entries(): Iterable<[number, T]>;} />

Collections (Seq)

<MemberLabel label="keySeq()" />

Returns a Seq of the keys in the Collection.

<Signature code={keySeq(): Seq.Indexed<number>;} />

<MemberLabel label="valueSeq()" />

Returns a Seq of the values in the Collection.

<Signature code={valueSeq(): Seq.Indexed<T>;} />

<MemberLabel label="entrySeq()" />

Returns a Seq of the [key, value] entries in the Collection.

<Signature code={entrySeq(): Seq.Indexed<[number, T]>;} />

Side effects

<MemberLabel label="forEach()" />

Calls the provided function for each value in the Collection. Returns the Collection.

<Signature code={forEach(fn: (value: T, index: number, iter: this) => void, context?: unknown): this;} />

Creating subsets

<MemberLabel label="slice()" />

Returns a new Collection.Indexed with the values between the given start and end indices.

<Signature code={slice(begin?: number, end?: number): this;} />

<MemberLabel label="rest()" />

Returns a new Collection.Indexed with all but the first value.

<Signature code={rest(): this;} />

<MemberLabel label="butLast()" />

Returns a new Collection.Indexed with all but the last value.

<Signature code={butLast(): this;} />

<MemberLabel label="skip()" />

Returns a new Collection.Indexed with the first n values removed.

<Signature code={skip(n: number): this;} />

<MemberLabel label="skipLast()" />

Returns a new Collection.Indexed with the last n values removed.

<Signature code={skipLast(n: number): this;} />

<MemberLabel label="skipWhile()" />

Returns a new Collection.Indexed with values skipped while the predicate function returns true.

<Signature code={skipWhile(predicate: (value: T, index: number, iter: this) => boolean, context?: unknown): this;} />

<MemberLabel label="skipUntil()" />

Returns a new Collection.Indexed with values skipped until the predicate function returns true.

<Signature code={skipUntil(predicate: (value: T, index: number, iter: this) => boolean, context?: unknown): this;} />

<MemberLabel label="take()" />

Returns a new Collection.Indexed with the first n values.

<Signature code={take(n: number): this;} />

<MemberLabel label="takeLast()" />

Returns a new Collection.Indexed with the last n values.

<Signature code={takeLast(n: number): this;} />

<MemberLabel label="takeWhile()" />

Returns a new Collection.Indexed with values taken while the predicate function returns true.

<Signature code={takeWhile(predicate: (value: T, index: number, iter: this) => boolean, context?: unknown): this;} />

<MemberLabel label="takeUntil()" />

Returns a new Collection.Indexed with values taken until the predicate function returns true.

<Signature code={takeUntil(predicate: (value: T, index: number, iter: this) => boolean, context?: unknown): this;} />

Reducing a value

<MemberLabel label="reduce()" />

Returns the accumulated result of calling the provided reducer function for each value in the Collection, from left to right.

<Signature code={reduce<R>(reducer: (previousValue: R | T, currentValue: T, index: number, iter: this) => R, initialValue?: R): R;} />

<MemberLabel label="reduceRight()" />

Returns the accumulated result of calling the provided reducer function for each value in the Collection, from right to left.

<Signature code={reduceRight<R>(reducer: (previousValue: R | T, currentValue: T, index: number, iter: this) => R, initialValue?: R): R;} />

<MemberLabel label="every()" />

Returns true if the predicate function returns a truthy value for every value in the Collection.

<Signature code={every(predicate: (value: T, index: number, iter: this) => boolean, context?: unknown): boolean;} />

<MemberLabel label="some()" />

Returns true if the predicate function returns a truthy value for any value in the Collection.

<Signature code={some(predicate: (value: T, index: number, iter: this) => boolean, context?: unknown): boolean;} />

<MemberLabel label="join()" />

Returns the concatenated string result of calling String(value) on every value in the Collection, separated by the given separator string.

<Signature code={join(separator?: string): string;} />

<MemberLabel label="isEmpty()" />

Returns true if the Collection has no values.

<Signature code={isEmpty(): boolean;} />

<MemberLabel label="count()" />

Returns the number of values in the Collection.

<Signature code={count(): number;} />

<MemberLabel label="countBy()" />

Returns a new Collection.Indexed with the number of times each value occurs in the Collection.

<Signature code={countBy(): Collection.Indexed<number>;} />

Comparison

<MemberLabel label="isSubset()" />

Returns true if this Collection.Indexed is a subset of the other Collection (i.e. all values in this Collection.Indexed are also in the other).

<Signature code={isSubset(other: unknown): other is this;} />

<MemberLabel label="isSuperset()" />

Returns true if this Collection.Indexed is a superset of the other Collection (i.e. this Collection.Indexed contains all values of the other).