| 1 |
/** A type for an array with at least one element. */ |
| 2 |
export type NonEmptyArray<T> = readonly [T, ...T[]]; |
| 3 |
|
| 4 |
/** Type guard for non-empty array. */ |
| 5 |
export function is_non_empty<T>( |
| 6 |
array: readonly T[], |
| 7 |
): array is NonEmptyArray<T> { |
| 8 |
return array.length > 0; |
| 9 |
} |
| 10 |
|
| 11 |
/** Get the last element of an non-empty array. */ |
| 12 |
export function last_element<T>(array: NonEmptyArray<T>): T { |
| 13 |
return array[array.length - 1] as T; |
| 14 |
} |
| 15 |
|
| 16 |
/** |
| 17 |
* Move an element from one position to another and return a copy. |
| 18 |
* |
| 19 |
* @param array - The array to operate on. |
| 20 |
* @param from - The array index of the element to move. |
| 21 |
* @param to - The array index to move it to. |
| 22 |
*/ |
| 23 |
export function move<T>( |
| 24 |
array: readonly T[], |
| 25 |
from: number, |
| 26 |
to: number, |
| 27 |
): readonly T[] { |
| 28 |
const moved = array[from]; |
| 29 |
if (moved != null) { |
| 30 |
const updated = array.toSpliced(from, 1); |
| 31 |
updated.splice(to, 0, moved); |
| 32 |
return updated; |
| 33 |
} else { |
| 34 |
return array; |
| 35 |
} |
| 36 |
} |