Skip to content
jshacks.dev
Functions

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.

1 min read
Summarize in AI

Filters grow complicated when each rule is an inline condition. Small tests can be combined into bigger ones with three helper functions.

JavaScript
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));
Text
[ '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.

Taggednode 24
Share

More snippets

Functions

Memoize a function with a Map

Memoize a function in JavaScript with a Map keyed by its argument, caching results including undefined. For single-argument pure functions on any Node.js.

1 min read
Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.