Apply function when condition is met

OSCC · 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

Recommended snippets

  • Convert function from variadic

    JavaScript, Function

    Takes a variadic function and returns a function that accepts an array of arguments.

  • 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.

  • Juxtapose functions

    JavaScript, Function

    Takes several functions as argument and returns a function that is the juxtaposition of those functions.