Skip to content

Commit

Permalink
Sort now tries to be consistent
Browse files Browse the repository at this point in the history
If sort by is set to amount, try sorting by date if amounts are same.
For sorting by date, if dates are equal sort by id.
This should hopefully make the transactions order consistent.

This also means that SortTransactions will almost never return zero which is a good thing I believe.
  • Loading branch information
JoseBritto committed Dec 11, 2023
1 parent 254d07e commit 3ede871
Showing 1 changed file with 17 additions and 13 deletions.
30 changes: 17 additions & 13 deletions NickvisionMoney.Shared/Controllers/AccountViewController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -410,19 +410,31 @@ private int SortTransactions(uint a, uint b)
}
else if (SortTransactionsBy == SortBy.Date)
{
compareTo = _account.Transactions[a].Date.CompareTo(_account.Transactions[b].Date);
compareTo = GetCompareToByDate();
}
else if (SortTransactionsBy == SortBy.Amount)
{
var aAmount = _account.Transactions[a].Amount * (_account.Transactions[a].Type == TransactionType.Income ? 1m : -1m);
var bAmount = _account.Transactions[b].Amount * (_account.Transactions[b].Type == TransactionType.Income ? 1m : -1m);
compareTo = aAmount.CompareTo(bAmount);
compareTo = GetCompareToByAmount();
}
if (!SortFirstToLast)
{
compareTo *= -1;
}
return compareTo;

int GetCompareToByDate()
{
var result = _account.Transactions[a].Date.CompareTo(_account.Transactions[b].Date);
return result == 0 ? a.CompareTo(b) : result; // If dates are equal, sort by id
}

int GetCompareToByAmount()
{
var aAmount = _account.Transactions[a].Amount * (_account.Transactions[a].Type == TransactionType.Income ? 1m : -1m);
var bAmount = _account.Transactions[b].Amount * (_account.Transactions[b].Type == TransactionType.Income ? 1m : -1m);
var result = aAmount.CompareTo(bAmount);
return result == 0 ? GetCompareToByDate() : result; // If amounts are equal, sort by date
}
}

/// <summary>
Expand Down Expand Up @@ -628,15 +640,7 @@ public async Task AddTransactionAsync(Transaction transaction)
if (res.Successful)
{
var transactions = _account.Transactions.Keys.ToList();
transactions.Sort((a, b) =>
{
var compareTo = SortTransactionsBy == SortBy.Date ? _account.Transactions[a].Date.CompareTo(_account.Transactions[b].Date) : a.CompareTo(b);
if (!SortFirstToLast)
{
compareTo *= -1;
}
return compareTo;
});
transactions.Sort(SortTransactions);
for (var i = 0; i < transactions.Count; i++)
{
if (transactions[i] == transaction.Id)
Expand Down

0 comments on commit 3ede871

Please sign in to comment.