Merge pull request #652 from yazeedb/add-when

Add when()
This commit is contained in:
Angelos Chalaris
2018-04-19 20:05:29 +03:00
committed by GitHub
4 changed files with 39 additions and 0 deletions

18
snippets/when.md Normal file
View File

@ -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
```

View File

@ -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

2
test/when/when.js Normal file
View File

@ -0,0 +1,2 @@
const when = (pred, whenTrue) => (x) => pred(x) ? whenTrue(x) : x;
module.exports = when;

18
test/when/when.test.js Normal file
View File

@ -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();
});