Module: arr

Array utilities for immutable operations

Source:

Methods

(static) add(arr, item) → {Array}

Immutably adds an item to an array (returns a new array).

Parameters:
Name Type Description
arr Array

The source array

item *

The item to add

Source:
Returns:

A new array with the item added at the end

Type
Array
Example
add([1, 2, 3], 4) // => [1, 2, 3, 4]

(static) contains(a, el) → {boolean}

Checks if an array or comma-separated string contains an element.

Parameters:
Name Type Description
a Array | string

The array or comma-separated string to check

el *

The element to look for

Source:
Returns:

True if the element is found, false otherwise

Type
boolean
Example
contains([1, 2, 3], 2) // => true
contains('a,b,c', 'b') // => true
contains([1, 2, 3], 4) // => false

(static) patch(arr, index, v) → {Array}

Immutably patches an array at a given index.

Parameters:
Name Type Description
arr Array

The source array

index number

The index to patch

v Object | function

The patch value to apply

Source:
Returns:

A new array with the patch applied

Type
Array
Example
// Patch with object (merges with existing object)
patch([{a: 1}, {b: 2}], 0, {c: 3}) // => [{a: 1, c: 3}, {b: 2}]

// Patch with function updater
patch([{count: 1}, {count: 2}], 0, (item) => ({...item, count: item.count + 1}))
// => [{count: 2}, {count: 2}]

// Patch at index beyond array length (extends array with undefined)
patch([1, 2], 5, 3) // => [1, 2, undefined, undefined, undefined, 3]

(static) remove(arr, item) → {Array}

Immutably removes the first occurrence of an item from an array. If the item is not found, returns the original array.

Parameters:
Name Type Description
arr Array

The source array

item *

The item to remove

Source:
Returns:

A new array with the item removed, or the original array if not found

Type
Array
Example
remove([1, 2, 3, 2], 2) // => [1, 3, 2]
remove([1, 2, 3], 4) // => [1, 2, 3]

(static) reorder(arr, from, to) → {Array}

Immutably reorders an array by moving an item from one index to another.

Parameters:
Name Type Description
arr Array

The source array

from number

The index of the item to move

to number

The index to move the item to

Source:
Returns:

A new array with the item moved

Type
Array
Example
reorder(['a', 'b', 'c', 'd', 'e'], 2, 1) // => ['a', 'c', 'b', 'd', 'e']
reorder(['a', 'b', 'c', 'd', 'e'], 3, 1) // => ['a', 'd', 'b', 'c', 'e']
reorder(['a', 'b', 'c', 'd', 'e'], 1, 3) // => ['a', 'c', 'd', 'b', 'e']
reorder(['a', 'b', 'c', 'd', 'e'], 3, 3) // => ['a', 'b', 'c', 'd', 'e'] // no change

(static) toggle(arr, item) → {Array}

Immutably toggles an item in an array (adds if not present, removes if present).

Parameters:
Name Type Description
arr Array

The source array

item *

The item to toggle

Source:
Returns:

A new array with the item toggled

Type
Array
Example
toggle([1, 2, 3], 2) // => [1, 3]
toggle([1, 2, 3], 4) // => [1, 2, 3, 4]