matches
util
Creates a function that performs a partial deep comparison between a given object and source.
Installation
Import
import { matches } from '@tulx/utils';Source Code
Implementation
/**
* Creates a function that performs a partial deep comparison between a given object and source.
*
* @param source - The object of property values to match.
* @returns Returns the new spec function.
*
* @example
* ```ts
* const objects = [
* { 'a': 1, 'b': 2, 'c': 3 },
* { 'a': 4, 'b': 5, 'c': 6 }
* ];
* filter(objects, matches({ 'a': 4, 'c': 6 })); // [{ 'a': 4, 'b': 5, 'c': 6 }]
* ```
*/
export function matches<T extends Record<string, unknown>>(
source: Record<string, unknown>
): (object: T) => boolean {
return function (object: T): boolean {
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
if (object[key] !== source[key]) {
return false;
}
}
}
return true;
};
}
Example
import { matches } from '@tulx/utils';
const objects = [
{ 'a': 1, 'b': 2, 'c': 3 },
{ 'a': 4, 'b': 5, 'c': 6 }
];
filter(objects, matches({ 'a': 4, 'c': 6 })); // [{ 'a': 4, 'b': 5, 'c': 6 }]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.
conforms
Creates a function that invokes the predicate properties of source with the corresponding property values of a given object.
constant
Creates a function that returns value.
defaultTo
Checks value to determine whether a default value should be returned in its place.