Build a predicate combinator with and and or
Build a predicate combinator in JavaScript with and, or and not helpers that combine test functions for filter. Works in any Node.js.
Filters grow complicated when each rule is an inline condition. Small tests can be combined into bigger ones with three helper functions.
const and = (...tests) => (x) => tests.every((test) => test(x));
const or = (...tests) => (x) => tests.some((test) => test(x));
const not = (test) => (x) => !test(x);
const isAdult = (user) => user.age >= 18;
const isActive = (user) => user.active;
const users = [
{ name: 'Ana', age: 30, active: true },
{ name: 'Bo', age: 15, active: true },
{ name: 'Cy', age: 40, active: false },
];
console.log(users.filter(and(isAdult, isActive)).map((u) => u.name));
console.log(users.filter(or(not(isAdult), not(isActive))).map((u) => u.name));[ 'Ana' ]
[ 'Bo', 'Cy' ]Each helper returns a new predicate, so they nest. every and some stop at the first result they can decide, so and skips the remaining tests after one fails.
Named predicates make the filter read like the rule. They help most when the same conditions are reused in several places. For a rule that is used once, a plain && in an arrow function is shorter and easier to follow.