Check an object against nested predicate rule functions
A notification service decides who gets an alert by checking each user against a set of rules, where every rule is a small function. Implement matchesRules(target, rules). It returns true when every rule passes for target, and false otherwise.
matchesRules(target, rules) // => true or false
rules is a plain object. Each own enumerable key names a property of target, and each value is either:
predicate(value, key, target). The rule passes when it returns a truthy value; ortarget is the property value.in operator finds it, so inherited properties (for example class getters) count, and a property whose value is undefined is present.Object.keys(rules) and stop at the first failing rule: later predicates are not called.target that have no rule are ignored. An empty rules object always matches.target is null or undefined, it matches only an empty rules object.target is another primitive, read its properties the way JavaScript does: 'hello'.length is 5, and (42).toFixed is a function. The predicate still receives the original primitive as its third argument.target or rules.const user = { name: 'Priya', age: 34, plan: 'pro', address: { country: 'IN', zip: '560001' } };
matchesRules(user, {
age: (age) => age >= 18,
plan: (plan) => plan === 'pro' || plan === 'team',
});
// => true
matchesRules(user, { age: (age) => age < 30 });
// => false
matchesRules(user, { address: { country: (c) => c === 'IN' } });
// => true (nested rules)
matchesRules(user, { email: () => true });
// => false ('email' is not present, so the predicate is never called)
matchesRules('hello', { length: (n) => n === 5 });
// => true
matchesRules(null, {});
// => true