Apply function when condition is met

JavaScript, Function, Logic · Oct 22, 2020

Returns a function that takes one argument and runs a callback if it's truthy or returns it if falsy.

  • Return a function expecting a single value, x, that returns the appropriate value based on pred.
const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x);
const doubleEvenNumbers = when(x => x % 2 === 0, x => x * 2);
doubleEvenNumbers(2); // 4
doubleEvenNumbers(1); // 1

More like this

  • JavaScript Logical Operations

    Get started with logical operations in JavaScript with this small snippet collection.

    Collection · 3 snippets

  • Generate until condition is met

    Creates a generator, that keeps producing new values until the given condition is met.

    JavaScript, Function · Jan 21, 2022

  • Generate while condition is met

    Creates a generator, that keeps producing new values as long as the given condition is met.

    JavaScript, Function · Jan 21, 2022

  • Logical or for functions

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

    JavaScript, Function · Oct 19, 2020