diff --git a/snippets/when.md b/snippets/when.md new file mode 100644 index 000000000..3ad0ceab7 --- /dev/null +++ b/snippets/when.md @@ -0,0 +1,18 @@ +### 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`. + +```js +const when = (pred, whenTrue) => (x) => pred(x) ? whenTrue(x) : x; +``` + +```js +const doubleEvenNumbers = when( + (x) => x % 2 === 0, + (x) => x * 2 +); +doubleEvenNumbers(2); // 4 +doubleEvenNumbers(1); // 1 +``` diff --git a/tag_database b/tag_database index 3a9b2cb60..68504d62a 100644 --- a/tag_database +++ b/tag_database @@ -291,6 +291,7 @@ URLJoin:string,utility,regexp UUIDGeneratorBrowser:browser,utility,random UUIDGeneratorNode:node,utility,random validateNumber:utility,math +when:function without:array words:string,regexp xProd:array,math diff --git a/test/when/when.js b/test/when/when.js new file mode 100644 index 000000000..3ce465630 --- /dev/null +++ b/test/when/when.js @@ -0,0 +1,2 @@ +const when = (pred, whenTrue) => (x) => pred(x) ? whenTrue(x) : x; +module.exports = when; \ No newline at end of file diff --git a/test/when/when.test.js b/test/when/when.test.js new file mode 100644 index 000000000..1a814190f --- /dev/null +++ b/test/when/when.test.js @@ -0,0 +1,18 @@ +const test = require('tape'); +const when = require('./when.js'); + +test('Testing when', (t) => { + //For more information on all the methods supported by tape + //Please go to https://github.com/substack/tape + t.true(typeof when === 'function', 'when is a Function'); + + const doubleEvenNumbers = when( + (x) => x % 2 === 0, + (x) => x * 2 + ); + + t.true(doubleEvenNumbers(2) === 4); + t.true(doubleEvenNumbers(1) === 1); + + t.end(); +});