Files
30-seconds-of-code/snippets/when.md
Isabelle Viktoria Maciohsek 27c168ce55 Bake date into snippets
2021-06-13 13:55:00 +03:00

538 B

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
when function,logic,beginner 2018-04-19T03:45:32+03:00 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