Skip to content

Commit 81fb66e

Browse files
committed
[SystemExtensions] ToSnakeCase()
1 parent aa4e4ed commit 81fb66e

File tree

2 files changed

+63
-3
lines changed

2 files changed

+63
-3
lines changed

src/10-Core/Wtq.UnitTest/Utils/SystemExtensionsTest.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,28 @@ public void EmptyOrWhiteSpaceToNull(string inp, string expected)
1313
{
1414
Assert.AreEqual(expected, inp.EmptyOrWhiteSpaceToNull());
1515
}
16+
17+
[TestMethod]
18+
[DataRow("", "")]
19+
[DataRow(" ", " ")]
20+
[DataRow("a", "a")]
21+
[DataRow("A", "a")]
22+
[DataRow("aa", "aa")]
23+
[DataRow("Aa", "aa")]
24+
[DataRow("AA", "a_a")]
25+
[DataRow("Snake", "snake")]
26+
[DataRow("SNAKE", "s_n_a_k_e")]
27+
[DataRow("ToSnakeCase", "to_snake_case")]
28+
[DataRow("to_snake_case", "to_snake_case")]
29+
[DataRow("To_Snake_Case", "to__snake__case")]
30+
public void ToSnakeCase(string inp, string expected)
31+
{
32+
Assert.AreEqual(expected, inp.ToSnakeCase());
33+
}
34+
35+
[TestMethod]
36+
public void ToSnakeCaseNull()
37+
{
38+
Assert.ThrowsException<ArgumentNullException>(() => ((string)null).ToSnakeCase());
39+
}
1640
}

src/10-Core/Wtq/Utils/SystemExtensions.cs

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,49 @@ public static IEnumerable<ValidationResult> Validate(this IValidatableObject val
2020
return validatable.Validate(new ValidationContext(new object()));
2121
}
2222

23-
public static string ExpandEnvVars(this string? src)
23+
/// <summary>
24+
/// Replace variables such as "%ENV_VAR%".<br/>
25+
/// E.g. "User %USER% is logged in" => "User username1 is logged in".<br/>
26+
/// Also replaces "~" with the path to the user's home directory.
27+
/// </summary>
28+
public static string ExpandEnvVars(this string source)
2429
{
25-
src ??= string.Empty;
30+
Guard.Against.Null(source);
2631

2732
return Environment
28-
.ExpandEnvironmentVariables(src)
33+
.ExpandEnvironmentVariables(source)
2934
?.Replace("~", WtqPaths.UserHome)
3035
?? string.Empty;
3136
}
37+
38+
/// <summary>
39+
/// "ToSnakeCase" => "to_snake_case".
40+
/// </summary>
41+
public static string ToSnakeCase(this string source)
42+
{
43+
Guard.Against.Null(source);
44+
45+
if (source.Length <= 1)
46+
{
47+
return source.ToLowerInvariant();
48+
}
49+
50+
var sb = new StringBuilder();
51+
sb.Append(char.ToLowerInvariant(source[0]));
52+
for (var i = 1; i < source.Length; ++i)
53+
{
54+
var c = source[i];
55+
if (char.IsUpper(c))
56+
{
57+
sb.Append('_');
58+
sb.Append(char.ToLowerInvariant(c));
59+
}
60+
else
61+
{
62+
sb.Append(c);
63+
}
64+
}
65+
66+
return sb.ToString();
67+
}
3268
}

0 commit comments

Comments
 (0)