UNPKG

1.61 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.propIf = propIf;
7exports.propIfNot = propIfNot;
8
9/**
10 * A simple ternary in the form of a function. The `add` argument is evaluated via JSON.parse
11 * (to turn "true" to `true`). And if the result is truthy, then `value` will be returned, otherwise `alternate` will be
12 * returned. This powers the (arguably more useful) methods returned from `getIfUtils`.
13 * @example
14 * propIf(true, 'value', 'alternate')
15 * // returns 'value'
16 * @example
17 * // Is falsy sensitive
18 * propIf(0, 'value', 'alternate')
19 * // returns 'alternate'
20 * @param {*} add The value to evaluate
21 * @param {*} value The value to return in a truthy case
22 * @param {*} alternate The value to return in a falsy case
23 * @return {*} The value based on whether `add` evaluates to truthy
24 */
25
26function propIf(add, value, alternate) {
27 return getValue(add) ? value : alternate;
28}
29
30/**
31 * This does the opposite of `propIf`. In fact, it just calls into it and swaps the `value` and `alternate` arguments
32 * 😄
33 * @param {*} add The value to evaluate
34 * @param {*} value The value to return in a falsy case
35 * @param {*} alternate The value to return in a truthy case
36 * @return {*} The value based on whether `add` evaluates to truthy
37 */
38function propIfNot(add, value, alternate) {
39 return propIf(add, alternate, value);
40}
41
42/**
43 * Parses the value as JSON. This way "true" evaluates to true and "23" evaluates to 23
44 * @private
45 * @param {*} val The value to parse
46 * @return {*} the parsed value
47 */
48function getValue(val) {
49 return JSON.parse(val);
50}
\No newline at end of file