Skip to content

Commit 8dffdef

Browse files
authored
refactor: reduce redundant code in NumericSort (#1417)
* Refactor the 2 do-loops into simpler while-loops and replace the use of "tmp1/2" char-arrays with calls to String.Substring(). * Rename the "loc1/2" variables to "subLen1/2", for clarity, since they represent the lengths of the two extracted Substrings. These changes make the logic more compact and easier to follow.
1 parent 158d926 commit 8dffdef

File tree

1 file changed

+12
-28
lines changed

1 file changed

+12
-28
lines changed

src/Models/NumericSort.cs

Lines changed: 12 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using Avalonia.Media;
23

34
namespace SourceGit.Models
45
{
@@ -12,50 +13,33 @@ public static int Compare(string s1, string s2)
1213
int marker1 = 0;
1314
int marker2 = 0;
1415

15-
char[] tmp1 = new char[len1];
16-
char[] tmp2 = new char[len2];
17-
1816
while (marker1 < len1 && marker2 < len2)
1917
{
2018
char c1 = s1[marker1];
2119
char c2 = s2[marker2];
22-
int loc1 = 0;
23-
int loc2 = 0;
2420

2521
bool isDigit1 = char.IsDigit(c1);
2622
bool isDigit2 = char.IsDigit(c2);
2723
if (isDigit1 != isDigit2)
2824
return c1.CompareTo(c2);
2925

30-
do
31-
{
32-
tmp1[loc1] = c1;
33-
loc1++;
34-
marker1++;
26+
int subLen1 = 1;
27+
while (marker1 + subLen1 < len1 && char.IsDigit(s1[marker1 + subLen1]) == isDigit1)
28+
subLen1++;
3529

36-
if (marker1 < len1)
37-
c1 = s1[marker1];
38-
else
39-
break;
40-
} while (char.IsDigit(c1) == isDigit1);
30+
int subLen2 = 1;
31+
while (marker2 + subLen2 < len2 && char.IsDigit(s2[marker2 + subLen2]) == isDigit2)
32+
subLen2++;
4133

42-
do
43-
{
44-
tmp2[loc2] = c2;
45-
loc2++;
46-
marker2++;
34+
string sub1 = s1.Substring(marker1, subLen1);
35+
string sub2 = s2.Substring(marker2, subLen2);
4736

48-
if (marker2 < len2)
49-
c2 = s2[marker2];
50-
else
51-
break;
52-
} while (char.IsDigit(c2) == isDigit2);
37+
marker1 += subLen1;
38+
marker2 += subLen2;
5339

54-
string sub1 = new string(tmp1, 0, loc1);
55-
string sub2 = new string(tmp2, 0, loc2);
5640
int result;
5741
if (isDigit1)
58-
result = loc1 == loc2 ? string.CompareOrdinal(sub1, sub2) : loc1 - loc2;
42+
result = (subLen1 == subLen2) ? string.CompareOrdinal(sub1, sub2) : (subLen1 - subLen2);
5943
else
6044
result = string.Compare(sub1, sub2, StringComparison.OrdinalIgnoreCase);
6145

0 commit comments

Comments
 (0)