1 /**
2     Truthy values: so not any of `false`, `null`, `0`, `""`, `none`, and `NaN`.
3 */
4 module ddash.utils.truthy;
5 
6 ///
7 unittest {
8     assert( isTruthy(true));
9     assert( isTruthy(1));
10     assert(!isTruthy(0));
11     assert( isTruthy((new int(3))));
12     assert(!isTruthy(((int[]).init)));
13     assert( isTruthy([1]));
14     assert(!isTruthy(double.nan));
15     assert(!isTruthy(0.0));
16     assert( isTruthy(1.0));
17 
18     class C {}
19     C c;
20     assert(!isTruthy(c));
21     c = new C;
22     assert( isTruthy(c));
23 
24     struct S {}
25     S s;
26     assert(!__traits(compiles, isTruthy(s)));
27 }
28 
29 import ddash.common;
30 
31 /**
32     Returns true if value is "truthy", i.e. not any of `false`, `null`, `0`, `""`, `none`, `NaN`, or `empty`.
33 
34     Params:
35         value = any value
36 
37     Returns:
38         true if truthy
39 
40     Since:
41         - 0.0.1
42 */
43 bool isTruthy(T)(auto ref T value) {
44     import std.traits: ifTestable, isArray, isPointer, isFloatingPoint;
45     import std.range: isInputRange;
46     static if (is(T == class) || isPointer!T)
47         return value !is null;
48     else static if (isArray!T)
49         return value.length != 0;
50     else static if (isInputRange!T)
51         return !value.empty;
52     else static if (isFloatingPoint!T)
53     {
54         import std.math: isNaN;
55         return value && !value.isNaN;
56     }
57     else static if (ifTestable!T)
58         return cast(bool)value;
59     else
60         static assert(
61             false,
62             "Cannot determine truthyness of type " ~ T.stringof
63         );
64 }
65 
66 /**
67     Returns true if value is "falsey", i.e. `false`, `null`, `0`, `""`, `none`, `NaN`, or `empty`.
68 
69     Since:
70         - 0.0.1
71 */
72 alias isFalsey = from!"std.functional".not!isTruthy;