Conforms ToLoading saved progress…

Conforms To

Implement conformsTo(object, source) — check whether an object satisfies a set of custom validation rules. The source argument is itself an object, but its values are not data to match against; they are predicate functions. A predicate is a function that takes a value and returns truthy ("this passes") or falsy ("this fails"). For every key in source, you run its predicate against the matching value on object, and conformsTo returns true only if all of them pass. This is the shape behind form validators, config checkers, and Lodash's _.conformsTo.

Signature

// object: a plain object whose values you want to validate.
// source: a plain object mapping the SAME keys to predicate functions.
//         Each predicate receives object[key] and returns truthy or falsy.
// returns: true iff source[key](object[key]) is truthy for EVERY key in source.
function conformsTo(object, source): boolean;

The keys that matter are the keys of source. Keys present on object but absent from source are never looked at.

Examples

// Every predicate passes → true.
conformsTo(
  { age: 36, name: 'Ada' },
  { age: (n) => n >= 18, name: (s) => s.length > 0 },
); // → true
// One predicate fails → the whole check is false.
conformsTo(
  { age: 36, name: '' },
  { age: (n) => n >= 18, name: (s) => s.length > 0 },
); // → false  (name is empty)
// A key in source that's missing on object: the predicate still runs,
// receiving `undefined`. The predicate's verdict decides the outcome.
conformsTo({ name: 'Ada' }, { email: (v) => typeof v === 'string' }); // → false
conformsTo({ name: 'Ada' }, { role:  (v) => v === undefined });       // → true

Notes

  • You invoke the predicates — you do not compare values. source[key] is a function, not an expected value. The check is source[key](object[key]), never object[key] === source[key].
  • A missing key is not special-cased. If source has a key that object lacks, the predicate runs on undefined and its result stands. A predicate like (v) => typeof v === 'string' will reject the absent key; a predicate like (v) => v === undefined will accept it.
  • An empty source returns true. With no rules to satisfy, the object vacuously conforms.
  • Extra keys on object are ignored. Only the keys listed in source are validated.
  • Coerce the verdict to a boolean. A predicate may return any truthy or falsy value (a number, a string, undefined); the return value of conformsTo is always true or false.
  • Don't worry about inherited keys, deeply nested schemas (a predicate can validate a nested value itself), or predicates that throw — assume each predicate returns a value.
Loading editor…