Logical or for functions

OSCC · JavaScript, Function, Logic · Oct 19, 2020

Checks if at least one function returns true for a given set of arguments.

  • Use the logical or (||) operator on the result of calling the two functions with the supplied args.
const either = (f, g) => (...args) => f(...args) || g(...args);
const isEven = num => num % 2 === 0;
const isPositive = num => num > 0;
const isPositiveOrEven = either(isPositive, isEven);
isPositiveOrEven(4); // true
isPositiveOrEven(3); // true

Recommended snippets

  • Argument coalescing factory

    JavaScript, Function

    Customizes a coalesce function that returns the first argument which is true based on the given validator.

  • Call functions with context

    JavaScript, Function

    Given a key and a set of arguments, call them when given a context.

  • Bind object method

    JavaScript, Function

    Creates a function that invokes the method at a given key of an object, optionally prepending any additional supplied parameters to the arguments.