-
Notifications
You must be signed in to change notification settings - Fork 237
Expand file tree
/
Copy pathHandlebarsUtils.cs
More file actions
77 lines (69 loc) · 2.31 KB
/
HandlebarsUtils.cs
File metadata and controls
77 lines (69 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using HandlebarsDotNet.Compiler;
using System.Collections;
namespace HandlebarsDotNet
{
public static class HandlebarsUtils
{
/// <summary>
/// Implementation of JS's `==`
/// </summary>
/// <param name="value"></param>
/// <param name="includeZero">Determined whether the numerical <c>0</c> is considered to be truthy. Default <c>false</c></param>
/// <returns></returns>
public static bool IsTruthy(object value, bool includeZero = false)
{
return !IsFalsy(value, includeZero);
}
/// <summary>
/// Implementation of JS's `!=`
/// </summary>
/// <param name="value">The value whose falsy-ness is to be determined</param>
/// <param name="includeZero">Determined whether the numerical <c>0</c> is considered to be truthy</param>
/// <returns></returns>
public static bool IsFalsy(object value, bool includeZero)
{
switch (value)
{
case UndefinedBindingResult _:
case null:
return true;
case bool b:
return !b;
case string s:
return s == string.Empty;
}
if (IsNumber(value) && !includeZero)
{
return !Convert.ToBoolean(value);
}
return false;
}
public static bool IsTruthyOrNonEmpty(object value, bool includeZero = false)
{
return !IsFalsyOrEmpty(value, includeZero);
}
public static bool IsFalsyOrEmpty(object value, bool includeZero = false)
{
if(IsFalsy(value, includeZero))
{
return true;
}
return value is IEnumerable enumerable && !enumerable.Any();
}
private static bool IsNumber(object value)
{
return value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is int
|| value is uint
|| value is long
|| value is ulong
|| value is float
|| value is double
|| value is decimal;
}
}
}