Files
30-seconds-of-code/snippets/when.md
Angelos Chalaris 611729214a Snippet format update
To match the starter (for the migration)
2019-08-13 10:29:12 +03:00

451 B

title, tags
title tags
when function,intermediate

Tests a value, x, against a predicate function. If true, return fn(x). Else, return x.

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