Skip to main content

interface SortedMap<K,V>

A type-invariant immutable Map of key type K, and value type V. In the Map, each key has exactly one value, and the Map cannot contain duplicate keys. See the Map documentation and the SortedMap API documentation

Companion namespace: SortedMap

Extends: RMapBase<K,V,Tp>

Implemented by: SortedMap.NonEmpty<K,V>, SortedMapEmpty<K,V>

Type parameters

NameDescription
Kthe key type
Vthe value type
note
  • The SortedMap keeps the inserted keys in sorted order according to the context's comp Comp instance.
example
const m1 = SortedMap.empty<number, string>()
const m2 = SortedMap.of([1, 'a'], [2, 'b'])

Properties

context

Returns the context associated to this collection instance.

Definition

readonly context: WithKeyValue<Tp, K, V>['context'];

Overrides

RMapBase.context

isEmpty

Returns true if the collection is empty.

Definition

readonly isEmpty: boolean;

example
HashMap.empty<number, number>().isEmpty    // => true
HashMap.of([1, 1], [2, 2]).isEmpty // => false

Overrides

VariantMapBase.isEmpty

size

Returns the number of entries

Definition

readonly size: number;

example
HashMap.of([1, 1], [2, 2]).size       // => 2

Overrides

VariantMapBase.size

Methods

[Symbol.iterator]

Returns a FastIterator instance used to iterate over the values of this Iterable.

Definition

[Symbol.iterator](): FastIterator<T>;

Overrides

FastIterable.[Symbol.iterator]

addEntries

Returns the collection with the entries from the given StreamSource entries added.

Definitions

addEntries<V2 extends V = V>(entries: StreamSource.NonEmpty<readonly [K, V2]>): WithKeyValue<Tp, K, V>['nonEmpty'];

addEntries<V2 extends V = V>(entries: StreamSource<readonly [K, V2]>): WithKeyValue<Tp, K, V>['normal'];

Type parameters

NameConstraintsDefaultDescription
V2V V

Parameters

NameTypeDescription
entriesStreamSource.NonEmpty<readonly [K, V2]>a StreamSource containing tuples with a key and value
example
HashMap.of([1, 'a']).addEntries([[2, 'b']]).toArray()   // => [[1, 'a'], [2, 'b']]

Overrides

RMapBase.addEntries

addEntry

Returns the collection with given entry added.

Definition

addEntry(entry: readonly [K, V]): WithKeyValue<Tp, K, V>['nonEmpty'];

Parameters

NameTypeDescription
entryreadonly [K, V]a tuple containing a key and value
example
HashMap.of([1, 'a']).addEntry([2, 'b']).toArray()   // => [[1, 'a'], [2, 'b']]
HashMap.of([1, 'a']).addEntry([1, 'b']).toArray() // => [[1, 'b']]

Overrides

RMapBase.addEntry

assumeNonEmpty

Returns the collection as a .NonEmpty type

Definition

assumeNonEmpty(): WithKeyValue<Tp, K, V>['nonEmpty'];

throws

RimbuError.EmptyCollectionAssumedNonEmptyError if the collection is empty

example
HashMap.empty<number, number>().assumeNonEmpty()   // => throws
const m: HashMap<number, number> = HashMap.of([1, 1], [2, 2])
const m2: HashMap.NonEmpty<number, number> = m // => compiler error
const m3: HashMap.NonEmpty<number, number> = m.assumeNonEmpty()
note

returns reference to this collection

Overrides

VariantMapBase.assumeNonEmpty

drop

Returns a SortedMap containing all but the the first amount of elements of this SortedMap.

Definition

drop(amount: number): SortedMap<K, V>;

Parameters

NameTypeDescription
amountnumberthe amount of elements to drop
note

a negative amount drops the last elements instead of the first, e.g. -2 is the last 2 elements

example
const m = SortedMap.of(['b', 2], ['d', 4], ['a', 1], ['c', 3]).asNormal();
console.log(m.drop(2).toArray())
// => [['c', ], ['d', 4]]
console.log(m.drop(-2).toArray())
// => [['a', 1], ['b', 2]]

filter

Returns a collection containing only those entries that satisfy given pred predicate.

Definition

filter(pred: (entry: readonly [K, V], index: number, halt: () => void) => boolean): WithKeyValue<Tp, K, V>['normal'];

Parameters

NameTypeDescription
pred(entry: readonly [K, V], index: number, halt: () => void) => booleana predicate function receiving:
- entry: the next entry
- index: the entry index
- halt: a function that, when called, ensures no next elements are passed
example
HashMap.of([1, 'a'], [2, 'b'], [3, 'c']).filter(entry => entry[0] === 2 || entry[1] === 'c').toArray()
// => [[2, 'b'], [3, 'c']]

Overrides

VariantMapBase.filter

forEach

Performs given function f for each entry of the collection, using given state as initial traversal state.

Definition

forEach(f: (entry: readonly [K, V], index: number, halt: () => void) => void, state?: TraverseState): void;

Parameters

NameTypeDescription
f(entry: readonly [K, V], index: number, halt: () => void) => voidthe function to perform for each entry, receiving:
- entry: the next tuple of a key and value
- index: the index of the element
- halt: a function that, if called, ensures that no new elements are passed
stateTraverseState(optional) the traverse state
example
HashMap.of([1, 'a'], [2, 'b'], [3, 'c']).forEach((entry, i, halt) => {
console.log([entry[1], entry[0]]);
if (i >= 1) halt();
})
// => logs ['a', 1] ['b', 2]
note

O(N)

Overrides

VariantMapBase.forEach

get

Returns the value associated with the given key, or given otherwise value if the key is not in the collection.

Definitions

get<UK = K>(key: RelatedTo<K, UK>): V | undefined;

get<UK, O>(key: RelatedTo<K, UK>, otherwise: OptLazy<O>): V | O;

Type parameters

NameDefaultDescription
UKK

Parameters

NameTypeDescription
keyRelatedTo<K, UK>the key to look for
example
const m = HashMap.of([1, 'a'], [2, 'b'])
m.get(2) // => 'b'
m.get(3) // => undefined
m.get(2, 'none') // => 'b'
m.get(3, 'none') // => 'none'

Overrides

VariantMapBase.get

getAtIndex

Returns the entry with its key at the given index of the key sort order of the SortedMap, or a fallback value (default: undefined) if the index is out of bounds.

Definitions

getAtIndex(index: number): readonly [K, V] | undefined;

getAtIndex<O>(index: number, otherwise: OptLazy<O>): readonly [K, V] | O;

Parameters

NameTypeDescription
indexnumberthe index in the key sort order
note

negative index values will retrieve the values from the end of the sort order, e.g. -1 is the last value

example
const m = SortedMap.of(['b', 2], ['d', 4], ['a', 1], ['c', 3]).asNormal();
console.log(m.getAtIndex(1))
// => ['b', 2]
console.log(m.getAtIndex(-1))
// => ['d', 4]
console.log(m.getAtIndex(10))
// => undefined
console.log(m.getAtIndex(10, 'q'))
// => 'q'

getKeyAtIndex

Returns the key at the given index of the key sort order of the SortedMap, or a fallback value (default: undefined) if the index is out of bounds.

Definitions

getKeyAtIndex(index: number): K | undefined;

getKeyAtIndex<O>(index: number, otherwise: OptLazy<O>): K | O;

Parameters

NameTypeDescription
indexnumberthe index in the key sort order
note

negative index values will retrieve the values from the end of the sort order, e.g. -1 is the last value

example
const m = SortedMap.of(['b', 2], ['d', 4], ['a', 1], ['c', 3]).asNormal();
console.log(m.getKeyAtIndex(1))
// => 'b'
console.log(m.getKeyAtIndex(-1))
// => 'd'
console.log(m.getKeyAtIndex(10))
// => undefined
console.log(m.getKeyAtIndex(10, 'q'))
// => 'q'

getValueAtIndex

Returns the value associated with the key at the given index of the key sort order of the SortedMap, or a fallback value (default: undefined) if the index is out of bounds.

Definitions

getValueAtIndex(index: number): V | undefined;

getValueAtIndex<O>(index: number, otherwise: OptLazy<O>): V | O;

Parameters

NameTypeDescription
indexnumberthe index in the key sort order
note

negative index values will retrieve the values from the end of the sort order, e.g. -1 is the last value

example
const m = SortedMap.of(['b', 2], ['d', 4], ['a', 1], ['c', 3]).asNormal();
console.log(m.getValueAtIndex(1))
// => 2
console.log(m.getValueAtIndex(-1))
// => 4
console.log(m.getValueAtIndex(10))
// => undefined
console.log(m.getValueAtIndex(10, 'q'))
// => 'q'

hasKey

Returns true if the given key is present in the collection.

Definition

hasKey<UK = K>(key: RelatedTo<K, UK>): boolean;

Type parameters

NameDefaultDescription
UKK

Parameters

NameTypeDescription
keyRelatedTo<K, UK>the key to look for
example
const m = HashMap.of([1, 'a'], [2, 'b'])
m.hasKey(2) // => true
m.hasKey(3) // => false

Overrides

VariantMapBase.hasKey

mapValues

Returns a collection with the same keys, but where the given mapFun function is applied to each entry value.

Definition

mapValues<V2>(mapFun: (value: V, key: K) => V2): (Tp & KeyValue<K, V2>)['normal'];

Type parameters

NameDescription
V2

Parameters

NameTypeDescription
mapFun(value: V, key: K) => V2a function taking a value and a key, and returning a new value
example
HashMap.of([1, 'a'], [2, 'abc']).mapValues(v => v.length).toArray()
// => [[1, 1], [2, 3]]

Overrides

VariantMapBase.mapValues

max

Returns the entry with the maximum key of the SortedMap, or a fallback value (default: undefined) if the SortedMap is empty.

Definitions

max(): readonly [K, V] | undefined;

max<O>(otherwise: OptLazy<O>): readonly [K, V] | O;

example
const m = SortedMap.of(['b', 2], ['d', 4], ['a', 1], ['c', 3]).asNormal();
console.log(m.max())
// => ['d', 4]
console.log(m.max('q'))
// => ['d', 4]
console.log(SortedMap.empty().max())
// => undefined
console.log(SortedMap.empty().max('q'))
// => 'q'

maxKey

Returns the maximum key of the SortedMap, or a fallback value (default: undefined) if the SortedMap is empty.

Definitions

maxKey(): K | undefined;

maxKey<O>(otherwise: OptLazy<O>): K | O;

example
const m = SortedMap.of(['b', 2], ['d', 4], ['a', 1], ['c', 3]).asNormal();
console.log(m.maxKey())
// => 'a'
console.log(m.maxKey('q'))
// => 'a'
console.log(SortedMap.empty().maxKey())
// => undefined
console.log(SortedMap.empty().maxKey('q'))
// => 'q'

maxValue

Returns the value associated with the maximum key of the SortedMap, or a fallback value (default: undefined) if the SortedMap is empty.

Definitions

maxValue(): V | undefined;

maxValue<O>(otherwise: OptLazy<O>): V | O;

example
const m = SortedMap.of(['b', 2], ['d', 4], ['a', 1], ['c', 3]).asNormal();
console.log(m.maxValue())
// => 4
console.log(m.maxValue('q'))
// => 4
console.log(SortedMap.empty().maxValue())
// => undefined
console.log(SortedMap.empty().maxValue('q'))
// => 'q'

min

Returns the entry with the minimum key of the SortedMap, or a fallback value (default: undefined) if the SortedMap is empty.

Definitions

min(): readonly [K, V] | undefined;

min<O>(otherwise: OptLazy<O>): readonly [K, V] | O;

example
const m = SortedMap.of(['b', 2], ['d', 4], ['a', 1], ['c', 3]).asNormal();
console.log(m.min())
// => ['a', 1]
console.log(m.min('q'))
// => ['a', 1]
console.log(SortedMap.empty().min())
// => undefined
console.log(SortedMap.empty().min('q'))
// => 'q'

minKey

Returns the minimum key of the SortedMap, or a fallback value (default: undefined) if the SortedMap is empty.

Definitions

minKey(): K | undefined;

minKey<O>(otherwise: OptLazy<O>): K | O;

example
const m = SortedMap.of(['b', 2], ['d', 4], ['a', 1], ['c', 3]).asNormal();
console.log(m.minKey())
// => 'a'
console.log(m.minKey('q'))
// => 'a'
console.log(SortedMap.empty().minKey())
// => undefined
console.log(SortedMap.empty().minKey('q'))
// => 'q'

minValue

Returns the value associated with the minimum key of the SortedMap, or a fallback value (default: undefined) if the SortedMap is empty.

Definitions

minValue(): V | undefined;

minValue<O>(otherwise: OptLazy<O>): V | O;

example
const m = SortedMap.of(['b', 2], ['d', 4], ['a', 1], ['c', 3]).asNormal();
console.log(m.minValue())
// => 1
console.log(m.minValue('q'))
// => 1
console.log(SortedMap.empty().minValue())
// => undefined
console.log(SortedMap.empty().minValue('q'))
// => 'q'

modifyAt

Returns the collection with the given atKey key modified according to given options.

Definition

modifyAt(atKey: K, options: {
    ifNew?: OptLazyOr<V, Token>;
    ifExists?: <V2 extends V = V>(currentEntry: V & V2, remove: Token) => V | Token;
  }): WithKeyValue<Tp, K, V>['normal'];

Parameters

NameTypeDescription
atKeyKthe key at which to modify the collection
options{
    ifNew?: OptLazyOr<V, Token>;
    ifExists?: <V2 extends V = V>(currentEntry: V & V2, remove: Token) => V | Token;
  }
an object containing the following information:
- ifNew: (optional) if the given atKey is not present in the collection, this value or function will be used to generate a new entry. If a function returning the token argument is given, no new entry is created.
- ifExists: (optional) if a value is associated with given atKey, this function is called with the given value to return a new value. As a second argument, a remove token is given. If the function returns this token, the current entry is removed.
example
const m = HashMap.of([1, 'a'], [2, 'b'])
m.modifyAt(3, { ifNew: 'c' }).toArray()
// => [[1, 'a'], [2, 'b'], [3, 'c']]
m.modifyAt(3, { ifNew: (none) => 1 < 2 ? none : 'c' }).toArray()
// => [[1, 'a'], [2, 'b']]
m.modifyAt(2, { ifExists: () => 'c' }).toArray()
// => [[1, 'a'], [2, 'c']]
m.modifyAt(2, { ifExists: (v) => v + 'z' }).toArray()
// => [[1, 'a'], [2, 'bz']]
m.modifyAt(2, { ifExists: (v, remove) => v === 'a' ? v : remove }).toArray()
// => [[1, 'a']]

Overrides

RMapBase.modifyAt

nonEmpty

Returns true if there is at least one entry in the collection, and instructs the compiler to treat the collection as a .NonEmpty type.

Definition

nonEmpty(): this is WithKeyValue<Tp, K, V>['nonEmpty'];

example
const m: HashMap<number, number> = HashMap.of([1, 1], [2, 2])
m.stream().first(0) // compiler allows fallback value since the Stream may be empty
if (m.nonEmpty()) {
m.stream().first(0) // compiler error: fallback value not allowed since Stream is not empty
}

Overrides

VariantMapBase.nonEmpty

removeKey

Returns the collection where the entry associated with given key is removed if it was part of the collection.

Definition

removeKey<UK = K>(key: RelatedTo<K, UK>): WithKeyValue<Tp, K, V>['normal'];

Type parameters

NameDefaultDescription
UKK

Parameters

NameTypeDescription
keyRelatedTo<K, UK>the key of the entry to remove
example
const m = HashMap.of([1, 'a'], [2, 'b'])
m.removeKey(2).toArray() // => [[1, 'a']]
m.removeKey(3) === m // true
note

guarantees same object reference if the key is not present

Overrides

VariantMapBase.removeKey

removeKeyAndGet

Returns a tuple containing the collection of which the entry associated with given key is removed, and the value that is associated with that key. If the key is not present, it will return undefined instead.

Definition

removeKeyAndGet<UK = K>(key: RelatedTo<K, UK>): [WithKeyValue<Tp, K, V>['normal'], V] | undefined;

Type parameters

NameDefaultDescription
UKK

Parameters

NameTypeDescription
keyRelatedTo<K, UK>the key of the entry to remove
example
const m = HashMap.of([1, 'a'], [2, 'b'])
const result = m.removeKeyAndGet(2)
if (result !== undefined) console.log([result[0].toString(), result[1]]) // => logs [HashMap(1 => 'a'), 'b']
console.log(m.removeKeyAndGet(3)) // => logs undefined

Overrides

VariantMapBase.removeKeyAndGet

removeKeys

Returns the collection where the entries associated with each key in given keys are removed if they were present.

Definition

removeKeys<UK = K>(keys: StreamSource<RelatedTo<K, UK>>): WithKeyValue<Tp, K, V>['normal'];

Type parameters

NameDefaultDescription
UKK

Parameters

NameTypeDescription
keysStreamSource<RelatedTo<K, UK>>a StreamSource of keys to remove
example
const m = HashMap.of([1, 'a'], [2, 'b'])
m.removeKeys([1, 3]).toArray() // => [[2, 'b']]
m.removeKeys([1, 3, 2]).toArray() // => []
m.removeKeys([3, 4, 5]) === m // => true
note

guarantees same object reference if none of the keys are present

Overrides

VariantMapBase.removeKeys

set

Returns the collection with the given key associated to the given value.

Definition

set(key: K, value: V): WithKeyValue<Tp, K, V>['nonEmpty'];

Parameters

NameTypeDescription
keyKthe entry key to add
valueVthe entry value to add
example
HashMap.of([1, 'a']).set(2, 'b').toArray()   // => [[1, 'a'], [2, 'b']]
HashMap.of([1, 'a']).set(1, 'b').toArray() // => [[1, 'b']]
note

if the key is already associated, the previous value will be 'replaced'

Overrides

RMapBase.set

slice

Returns a SortedMap containing only those entries whose keys are within the given keyRange.

Definition

slice(keyRange: Range<K>): SortedMap<K, V>;

Parameters

NameTypeDescription
keyRangeRange<K>a Range defining the keys to include
example
const m = SortedMap.of(['b', 2], ['d', 4], ['a', 1], ['c', 3]).asNormal();
console.log(m.slice({ start: 'b', end: 'c' }).toArray())
// => [['b', 2], ['c', 3]]

sliceIndex

Returns a SortedMap containing only those entries that are within the given range index range of they key sort order.

Definition

sliceIndex(range: IndexRange): SortedMap<K, V>;

Parameters

NameTypeDescription
rangeIndexRangean IndexRange defining the sort order indices to include.
example
const m = SortedMap.of(['b', 2], ['d', 4], ['a', 1], ['c', 3]).asNormal();
console.log(m.sliceIndex({ start: 1, amount: 2 }).toArray())
// => [['b', 2], ['c', 3]]

stream

undocumented

Definition

stream(reversed?: boolean): Stream<readonly [K, V]>;

Parameters

NameTypeDescription
reversedboolean

Overrides

VariantMapBase.stream

streamKeys

undocumented

Definition

streamKeys(reversed?: boolean): Stream<K>;

Parameters

NameTypeDescription
reversedboolean

Overrides

VariantMapBase.streamKeys

streamRange

Returns a Stream of sorted entries of this collection within the given keyRange.

Definition

streamRange(keyRange: Range<K>, reversed?: boolean): Stream<readonly [K, V]>;

Parameters

NameTypeDescription
keyRangeRange<K>the range of keys to include in the stream
reversedboolean
example
const m = SortedMap.of(['b', 2], ['d', 4], ['a', 1], ['c', 3]);
console.log(m.streamRange({ start: 'b', end: 'c' }).toArray())
// => ['b', 'c']

streamSliceIndex

Returns a Stream of sorted entries of this collection within the given range index range.

Definition

streamSliceIndex(
  range: IndexRange,
  reversed?: boolean
 ): Stream<readonly [K, V]>;

Parameters

NameTypeDescription
rangeIndexRangethe range of keys to include in the stream
reversedboolean
 
example
const m = SortedMap.of(['b', 2], ['d', 4], ['a', 1], ['c', 3]);
console.log(m.streamSliceIndex({ start: 1, amount: 2 }).toArray())
// => [['b', 2], ['c', 3]]

streamValues

undocumented

Definition

streamValues(reversed?: boolean): Stream<V>;

Parameters

NameTypeDescription
reversedboolean

Overrides

VariantMapBase.streamValues

take

Returns a SortedMap containing the the first amount of elements of this SortedMap.

Definition

take(amount: number): SortedMap<K, V>;

Parameters

NameTypeDescription
amountnumberthe amount of elements to keep
note

a negative amount takes the last elements instead of the first, e.g. -2 is the last 2 elements

example
const m = SortedMap.of(['b', 2], ['d', 4], ['a', 1], ['c', 3]).asNormal();
console.log(m.take(2).toArray())
// => [['a', 1], ['b', 2]]
console.log(m.take(-2).toArray())
// => [['c', ], ['d', 4]]

toArray

Returns an array containing all entries in this collection.

Definition

toArray(): (readonly [K, V])[];

example
HashMap.of([1, 'a'], [2, 'b']).toArray()   // => [[1, 'a'], [2, 'b']]
note

O(log(N)) @note it is safe to mutate the returned array, however, the array elements are not copied, thus should be treated as read-only

Overrides

VariantMapBase.toArray

toBuilder

Returns a builder object containing the entries of this collection.

Definition

toBuilder(): WithKeyValue<Tp, K, V>['builder'];

example
const builder: HashMap.Builder<number, string> = HashMap.of([1, 'a'], [2, 'b']).toBuilder()

Overrides

RMapBase.toBuilder

toJSON

Returns a JSON representation of this collection.

Definition

toJSON(): ToJSON<(readonly [K, V])[]>;

example
HashMap.of([1, 'a'], [2, 'b']).toJSON()   // => { dataType: 'HashMap', value: [[1, 'a'], [2, 'b']] }

Overrides

VariantMapBase.toJSON

toString

Returns a string representation of this collection.

Definition

toString(): string;

example
HashMap.of([1, 'a'], [2, 'b']).toString()   // => HashMap(1 => 'a', 2 => 'b')

Overrides

VariantMapBase.toString

updateAt

Returns the collection where the value associated with given key is updated with the given update value or update function.

Definition

updateAt<UK = K>(key: RelatedTo<K, UK>, update: RMapBase.Update<V>): WithKeyValue<Tp, K, V>['normal'];

Type parameters

NameDefaultDescription
UKK

Parameters

NameTypeDescription
keyRelatedTo<K, UK>the key of the entry to update
updateRMapBase.Update<V>a new value or function taking the current value and returning a new value
example
const m = HashMap.of([1, 'a'], [2, 'b'])
m.updateAt(3, 'a').toArray()
// => [[1, 'a'], [2, 'b']]
m.updateAt(2, 'c').toArray()
// => [[1, 'a'], [2, 'c']]
m.updateAt(2, v => v + 'z')
// => [[1, 'a'], [2, 'cz]]

Overrides

RMapBase.updateAt