Files
30-seconds-of-code/snippets/js/s/conditionally-apply-function.md
Angelos Chalaris 9d032ce05e Rename js snippets
2023-05-19 20:23:47 +03:00

587 B

title, type, language, tags, cover, dateModified
title type language tags cover dateModified
Apply function when condition is met snippet javascript
function
logic
flower-portrait-8 2020-10-22T20:24:44+03:00

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