30秒学会 JavaScript 片段 · 2018年11月20日

30秒学会 JavaScript 片段 – when

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