ex-int-02-meet-the-teacher/MeetTheTeacher/Model/Comparison/ComparerBase.cs
2025-04-24 23:34:37 +02:00

76 lines
2.3 KiB
C#

namespace MeetTheTeacher.Model.Comparison;
/// <summary>
/// Base class for comparers which allow switching between ascending and descending mode
/// </summary>
public abstract class ComparerBase
{
/// <summary>
/// Creates a new instance of <see cref="ComparerBase" /> configured to sort in ascending or descending order
/// </summary>
/// <param name="ascending">Flag indicating if items should be sorted in ascending order; descending if false</param>
protected ComparerBase(bool ascending)
{
Ascending = ascending;
}
/// <summary>
/// Gets if the comparer is configured to sort in ascending order; descending if false
/// </summary>
protected bool Ascending { get; }
/// <summary>
/// Checks if a <see cref="Teacher"/> is null
/// </summary>
/// <param name="x">Teacher x</param>
/// <param name="y">Teacher y</param>
/// <returns>0 if both are null, the comparison if only one is null and 2 if both are NOT null</returns>
protected int CheckNull(Teacher? x, Teacher? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null)
{
return Ascending ? 1 : -1;
}
if (y == null)
{
return Ascending ? -1 : 1;
}
return 2;
}
/// <summary>
/// Compares the two enums
/// </summary>
/// <param name="x">First enum</param>
/// <param name="y">Second enum</param>
/// <typeparam name="TEnum">Enum Type</typeparam>
/// <returns>The comparison</returns>
protected int CompareEnum<TEnum>(TEnum? x, TEnum? y) where TEnum : struct, Enum
{
if (!x.HasValue && !y.HasValue)
{
return 0;
}
if (!x.HasValue)
{
return -1;
}
if (!y.HasValue)
{
return 1;
}
return x.Value.CompareTo(y.Value);
}
/// <summary>
/// Applies the correct direction
/// </summary>
/// <param name="comparison">The comparison</param>
/// <returns><param name="comparison"> if <see cref="Ascending"/> is true, else returns negated value</param></returns>
protected int ApplyCorrectDirection(int comparison) => Ascending ? comparison : -comparison;
}