Back to Functions

conformsTo

lang

Checks if object conforms to source by invoking the predicate properties of source with the corresponding property values of object.

Installation

Import
import { conformsTo } from '@tulx/utils';

Source Code

Implementation
/**
 * Checks if object conforms to source by invoking the predicate properties of source with the corresponding property values of object.
 *
 * @param object - The object to inspect.
 * @param source - The object of property predicates to conform to.
 * @returns Returns true if object conforms, else false.
 *
 * @example
 * ```ts
 * const object = { 'a': 1, 'b': 2 };
 * conformsTo(object, { 'b': (n: number) => n > 1 }); // true
 * conformsTo(object, { 'b': (n: number) => n > 2 }); // false
 * ```
 */
export function conformsTo<T extends Record<string, unknown>>(
  object: T,
  source: Record<string, (value: unknown) => boolean>
): 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 { conformsTo } from '@tulx/utils';

const object = { 'a': 1, 'b': 2 };
conformsTo(object, { 'b': (n: number) => n > 1 }); // true
conformsTo(object, { 'b': (n: number) => n > 2 }); // false

Related Functions