conforms
util
Creates a function that invokes the predicate properties of source with the corresponding property values of a given object.
Installation
Import
import { conforms } from '@tulx/utils';Source Code
Implementation
/**
* Creates a function that invokes the predicate properties of source with the corresponding property values of a given object.
*
* @param source - The object of property predicates to conform to.
* @returns Returns the new function.
*
* @example
* ```ts
* const objects = [
* { 'a': 2, 'b': 1 },
* { 'a': 1, 'b': 2 }
* ];
* filter(objects, conforms({ 'b': (n: number) => n > 1 })); // [{ 'a': 1, 'b': 2 }]
* ```
*/
export function conforms<T extends Record<string, unknown>>(
source: Record<string, (value: unknown) => boolean>
): (object: T) => boolean {
return function (object: T): boolean {
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
const predicate = source[key];
const value = object[key];
if (!predicate(value)) {
return false;
}
}
}
return true;
};
}
Example
import { conforms } from '@tulx/utils';
const objects = [
{ 'a': 2, 'b': 1 },
{ 'a': 1, 'b': 2 }
];
filter(objects, conforms({ 'b': (n: number) => n > 1 })); // [{ 'a': 1, 'b': 2 }]Related Functions
attempt
Attempts to invoke func, returning either the result or the caught error object.
bindAll
Binds methods of an object to the object itself, overwriting the existing method.
cond
Creates a function that iterates over pairs and invokes the corresponding function of the first predicate to return truthy.
constant
Creates a function that returns value.
defaultTo
Checks value to determine whether a default value should be returned in its place.
flow
Creates a function that returns the result of invoking the given functions with the this binding of the created function.