some
The some utility checks if at least one element in an array satisfies a given condition. It stops iterating as soon as it finds a match, making it efficient for large datasets. Unlike the native Array.prototype.some, this version supports asynchronous predicates.
Implementation
View Source Code
ts
import { assert } from '../function/assert';
import { IS_ARRAY_ERROR_MSG, isArray } from '../typed/isArray';
import type { Predicate } from '../types';
/**
* Checks if at least one element in the array satisfies the provided predicate function.
*
* @example
* ```ts
* some([1, 2, 3], (n) => n === 2) // true
* some([1, 2, 3], (n) => n === 4) // false
* ```
*
* @param array - The array to be checked.
* @param predicate - The function to test each element of the array.
*
* @returns `true` if at least one element satisfies the predicate, otherwise `false`.
*
* @throws {TypeError} If the provided array is not an array.
*/
export function some<T>(array: T[], predicate: Predicate<T>) {
assert(isArray(array), IS_ARRAY_ERROR_MSG, { args: { array }, type: TypeError });
for (let index = 0; index < array.length; index++) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
some.fp = true;Features
- Isomorphic: Works in both Browser and Node.js.
- Short-circuiting: Stops execution as soon as a match is found for better performance.
- Type-safe: Properly typed predicate support.
API
ts
function some<T>(array: T[], predicate: (item: T, index: number, array: T[]) => boolean): boolean;Parameters
array: The array to check.predicate: The function to test each element. It receives:item: The current element.index: The index of the current element.array: The original array.
Returns
trueif the predicate returns truthy for any element; otherwise,false.
Examples
Basic Validation
ts
import { some } from '@vielzeug/toolkit';
const numbers = [1, 3, 5, 7, 8];
// Check for even numbers
const hasEven = some(numbers, (x) => x % 2 === 0); // trueChecking Object Properties
ts
import { some } from '@vielzeug/toolkit';
const users = [
{ id: 1, role: 'user' },
{ id: 2, role: 'editor' },
{ id: 3, role: 'user' },
];
// Check if any admin exists
const hasAdmin = some(users, (u) => u.role === 'admin'); // falseImplementation Notes
- Throws
TypeErrorif the first argument is not an array. - Returns
falsefor an empty array, regardless of the predicate. - Does not modify the original array.