Files
30-seconds-of-code/snippets/when.md
Isabelle Viktoria Maciohsek aa425812b4 Update snippet descriptions
2020-10-22 20:24:44 +03:00

462 B

title, tags
title tags
when function,logic,beginner

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