Arrays
Utility functions for working with arrays.
Make Array
Generates an array of a specified length. If a value is provided, the array will be filled with that value. Otherwise, it will contain consecutive numbers starting from 1.
export function makeArray(length: number, fillValue?: any) {
return Array.from({ length }, (_, i) => fillValue || i + 1);
}Compare Arrays
Performs an element-wise comparison between two arrays of primitives.
export function areEqual<T extends Array<Primitive>>(a: T, b: T) {
if (a === b) return true;
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i] && !(Number.isNaN(a[i]) && Number.isNaN(b[i]))) return false;
}
return true;
}Get Element and Index from Array
Searches through an array and returns the first element that satisfies the given predicate, along with its index. If no match is found, it returns [null, -1].
export function findElement<T>(array: T[], predicate: (item: T) => boolean): [T, number] | [null, -1] {
for (let i = 0; i < array.length; i++) {
if (predicate(array[i])) {
return [array[i], i];
}
}
return [null, -1];
}