Skip to content

Refactor: reduce redundant code in NumericSort.Compare() #1417

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 13, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 12 additions & 28 deletions src/Models/NumericSort.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using Avalonia.Media;

namespace SourceGit.Models
{
Expand All @@ -12,50 +13,33 @@ public static int Compare(string s1, string s2)
int marker1 = 0;
int marker2 = 0;

char[] tmp1 = new char[len1];
char[] tmp2 = new char[len2];

while (marker1 < len1 && marker2 < len2)
{
char c1 = s1[marker1];
char c2 = s2[marker2];
int loc1 = 0;
int loc2 = 0;

bool isDigit1 = char.IsDigit(c1);
bool isDigit2 = char.IsDigit(c2);
if (isDigit1 != isDigit2)
return c1.CompareTo(c2);

do
{
tmp1[loc1] = c1;
loc1++;
marker1++;
int subLen1 = 1;
while (marker1 + subLen1 < len1 && char.IsDigit(s1[marker1 + subLen1]) == isDigit1)
subLen1++;

if (marker1 < len1)
c1 = s1[marker1];
else
break;
} while (char.IsDigit(c1) == isDigit1);
int subLen2 = 1;
while (marker2 + subLen2 < len2 && char.IsDigit(s2[marker2 + subLen2]) == isDigit2)
subLen2++;

do
{
tmp2[loc2] = c2;
loc2++;
marker2++;
string sub1 = s1.Substring(marker1, subLen1);
string sub2 = s2.Substring(marker2, subLen2);

if (marker2 < len2)
c2 = s2[marker2];
else
break;
} while (char.IsDigit(c2) == isDigit2);
marker1 += subLen1;
marker2 += subLen2;

string sub1 = new string(tmp1, 0, loc1);
string sub2 = new string(tmp2, 0, loc2);
int result;
if (isDigit1)
result = loc1 == loc2 ? string.CompareOrdinal(sub1, sub2) : loc1 - loc2;
result = (subLen1 == subLen2) ? string.CompareOrdinal(sub1, sub2) : (subLen1 - subLen2);
else
result = string.Compare(sub1, sub2, StringComparison.OrdinalIgnoreCase);

Expand Down
Loading