jwidget/ArrayUtils

jWidget utilities for native JavaScript arrays.

Consumption

import * as ArrayUtils from "jwidget/ArrayUtils";

addAll#

<T>(arr: T[], items: Iterable<T>, index?: number)

arr
Array to modify.
items
Items to add.
index
Index of an item to add the new ones before. By default, appends the items to the end of array.

Adds a range of new items to an array.

backForEach#

<T>(arr: readonly T[], callback: (item: T, index: number) => void)

arr
Array.
callback
Callback.

Iterates through array items in backward order.

binarySearch#

<T>(arr: readonly T[], isHigher: (value: T) => boolean): number

arr
Sorted array.
isHigher
Should return true if the argument is "higher" than the searched value.
returns
Array index.

Determines index of the first item the isHigher callback returns true for. If such an item does not exist, returns the array length. The input array must be ordered in such a way that all values such that !isHigher(value) go before isHigher(value).

invert#

(arr: readonly number[]): number[]

arr
Array to invert.
returns
New inverted array.

Builds a new array by the rule: result[arr[i]] === i and returns it.

isIdentity#

(arr: readonly number[]): boolean

arr
Array to inspect.
returns
Every item in arr is equal to its index: arr[i] === i.

merge#

<T>(arrays: readonly (readonly T[])[]): T[]

arrays
Array of subarrays.
returns
Merged array.

Builds a new array consisting of subarray items in the same order.

move#

<T>(arr: T[], fromIndex: number, toIndex: number): T

arr
Array to modify.
fromIndex
Index of an item to move.
toIndex
Index to move the item to.
returns
Value of the moved item.

Moves an item in an array.

tryReorder#

<T>(arr: T[], indexArray: readonly number[]): T[]

arr
Array to modify.
indexArray
Index array. Item with index i will be moved to index indexArray[i]. Must contain all indexes from 0 to (length - 1).
returns
Old array contents. If the array is not modified, returns undefined.

Reorders array items.

trySplice#

<T>(arr: T[], segmentsToRemove: Iterable<IBindableArray.IndexCount>, segmentsToAdd: Iterable<IBindableArray.IndexItems<T>>): IBindableArray.SpliceResult<T>

arr
Array to modify.
segmentsToRemove
Array of segments to remove sorted by index asc. Segments are removed in backward order.
segmentsToAdd
Array of segments to insert sorted by index asc. Segments are inserted in forward order.
returns
Splice result. If the array is not modified, returns undefined.

Removes and inserts item ranges.