moveItem
EditMoves an item to another existing index without mutating the array.
/** Moves one array item to another index without mutating the input. */export const moveItem = <const T>( array: readonly T[], fromIndex: number, toIndex: number,): T[] => { if (!Number.isSafeInteger(fromIndex) || !Number.isSafeInteger(toIndex)) { throw new RangeError("indexes must be safe integers"); } const result: T[] = []; for (let index = 0; index < array.length; index += 1) { if (!Object.hasOwn(array, index)) { throw new TypeError("array must not contain empty slots"); } result.push(array[index] as T); } const length = result.length; const from = fromIndex < 0 ? length + fromIndex : fromIndex; const to = toIndex < 0 ? length + toIndex : toIndex; if (from < 0 || from >= length || to < 0 || to >= length) { throw new RangeError("indexes must refer to existing items"); } if (from === to) return result;
const value = result[from] as T; result.splice(from, 1); result.splice(to, 0, value); return result;};Download
Section titled “Download”wget -O src/lib/moveItem.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/moveItem.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/functions "$temp_dir" && mv "$temp_dir/moveItem.ts" src/lib/moveItem.ts && rm -r "$temp_dir"Examples
Section titled “Examples”import { moveItem } from "./moveItem";
const ordered = moveItem(["first", "second", "third"], 2, 0);// ["third", "first", "second"]array(readonly T[]) — Dense source values. Sparse arrays are rejected.fromIndex(number) — Existing source index; negatives count from the end.toIndex(number) — Existing destination index; negatives count from the end.