every
collection
Checks if predicate returns truthy for all elements of collection.
Installation
Import
import { every } from '@tulx/utils';Source Code
Implementation
/**
* Checks if predicate returns truthy for all elements of collection.
*
* @param collection - The collection to iterate over.
* @param predicate - The function invoked per iteration.
* @returns Returns true if all elements pass the predicate check, else false.
*
* @example
* ```ts
* every([true, 1, null, 'yes'], Boolean); // false
* every([true, 1], Boolean); // true
* ```
*/
export function every<T>(
collection: readonly T[] | Record<string, T>,
predicate?: (
value: T,
index: number | string,
collection: readonly T[] | Record<string, T>
) => boolean
): boolean {
if (!predicate) {
predicate = (value) => Boolean(value);
}
if (Array.isArray(collection)) {
for (let i = 0; i < collection.length; i++) {
if (!predicate(collection[i], i, collection)) {
return false;
}
}
} else {
const record = collection as Record<string, T>;
for (const key in record) {
if (Object.prototype.hasOwnProperty.call(record, key)) {
if (!predicate(record[key], key, record)) {
return false;
}
}
}
}
return true;
}
Example
import { every } from '@tulx/utils';
every([true, 1, null, 'yes'], Boolean); // false
every([true, 1], Boolean); // trueRelated Functions
countBy
Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The corresponding value of each key is the number of times the key was returned by iteratee.
each
Iterates over elements of collection and invokes iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection).
eachRight
This method is like each except that it iterates over elements of collection from right to left.
filter
Iterates over elements of collection, returning an array of all elements predicate returns truthy for.
find
Iterates over elements of collection, returning the first element predicate returns truthy for.
findLast
This method is like find except that it iterates over elements of collection from right to left.