18
snippets/when.md
Normal file
18
snippets/when.md
Normal 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
|
||||
```
|
||||
@ -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
2
test/when/when.js
Normal 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
18
test/when/when.test.js
Normal 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();
|
||||
});
|
||||
Reference in New Issue
Block a user