1 | /** @module logic **/
|
2 | const { curry } = require('../fp');
|
3 |
|
4 | /** Will evaluate the first function, if it throws any exception will evaluate the second one.
|
5 | * @argument {Function} mainFn function to be executed.
|
6 | * @argument {Function|*} failOver function or value to fail over if first one fails.
|
7 | * @returns {Function} excepting to receive fn arguments.
|
8 | * @example
|
9 | * const jsonOr = either(parse.JSON,value => `Cannot parse ${value} as json`)
|
10 | * jsonOr(null) // -> "Cannot parse null as json"
|
11 | * @example
|
12 | * const jsonOr = either(parse.JSON,33)
|
13 | * jsonOr(null) // -> 33
|
14 | * jsonOr('{"a":1}') // -> {a:1}
|
15 | * @method
|
16 | */
|
17 | const either = (mainFn, failOver) => (...arg) => {
|
18 | try {
|
19 | return mainFn(...arg);
|
20 | } catch (e) {
|
21 | return fnOrValue(failOver, e);
|
22 | }
|
23 | };
|
24 | /** Given a value that can be a function if it's a function we call it passing the data to it
|
25 | * if not we just return it
|
26 | * @argument {Function|*} fnOrVal a function or any value
|
27 | * @arugment {*} data any kind of data
|
28 | * @example
|
29 | * fnOrValue(3,4) // -> 3
|
30 | * fnOrValue(4,null) // -> 4
|
31 | * fnOrValue(x => x+1,4) // -> 5
|
32 | * fnOrValue(x => x*2,4) // -> 8
|
33 | * @returns {*}
|
34 | * @method
|
35 | */
|
36 | const fnOrValue = curry((fnOrVal, data) => (typeof fnOrVal === 'function' ? fnOrVal(data) : fnOrVal));
|
37 | /** Function that returns the passed value
|
38 | * @argument {*} x any value
|
39 | * @returns {*} any value
|
40 | * @example
|
41 | * [1,2].map(identity) // -> [1,2]
|
42 | * @method
|
43 | */
|
44 | const identity = x => x;
|
45 | /** Function that negates any passed function value
|
46 | * @argument {Function} fn function to be negated
|
47 | * @returns {Boolean} negated boolean value
|
48 | * @example
|
49 | * const isNumber = not(isNaN)
|
50 | * isNumber(33) // -> true
|
51 | * @method
|
52 | */
|
53 | const not = fn => (...args) => !fn(...args);
|
54 |
|
55 | module.exports = { either, fnOrValue, identity, not };
|