every
The every utility checks if all elements in an array pass the provided test function. It returns true only if the predicate returns truthy for every single element. It short-circuits and returns false as soon as a non-matching element is found.
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 all elements in an array pass a predicate function.
*
* @example
* ```ts
* const arr = [1, 2, 3, 4, 5];
* const isEven = (num) => num % 2 === 0;
* every(arr, isEven); // false
* ```
*
* @param array - The array to check.
* @param predicate - The predicate function to test each element.
*
* @returns true if all elements pass the predicate test, else false.
*
* @throws {TypeError} If the first argument is not an array.
*/
export function every<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 false;
}
}
return true;
}
every.fp = true;Features
- Isomorphic: Works in both Browser and Node.js.
- Short-circuiting: Stops execution as soon as a failure is found for better performance.
- Type-safe: Properly typed predicate support.
API
ts
function every<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 every element; otherwise,false.
Examples
Basic Validation
ts
import { every } from '@vielzeug/toolkit';
const numbers = [2, 4, 6, 8];
// Check if all numbers are even
const allEven = every(numbers, (x) => x % 2 === 0); // trueChecking Object Collections
ts
import { every } from '@vielzeug/toolkit';
const tasks = [
{ id: 1, completed: true },
{ id: 2, completed: true },
{ id: 3, completed: false },
];
// Check if all tasks are finished
const allDone = every(tasks, (t) => t.completed); // falseImplementation Notes
- Throws
TypeErrorif the first argument is not an array. - Returns
truefor an empty array (vacuous truth). - Does not modify the original array.