rj-action-library/Runtime/Sorting/ValueSorter.cs

79 lines
1.6 KiB
C#

using System.Collections;
using System.Collections.Generic;
using System;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Rokojori
{
public class ValueSorter<T>
{
Func<T,float> getFloatValue;
bool reverse_highestFirst = false;
Dictionary<T,float> cachedValues = new Dictionary<T, float>();
public static ValueSorter<T> Create( Func<T,float> getFloatValue, bool reverse_highestFirst = false )
{
var vs = new ValueSorter<T>();
vs.getFloatValue = getFloatValue;
vs.reverse_highestFirst = reverse_highestFirst;
return vs;
}
public void ClearCache()
{
cachedValues.Clear();
}
public float GetValue( T t )
{
if ( ! cachedValues.ContainsKey( t ) )
{
cachedValues[ t ] = getFloatValue( t );;
}
return cachedValues[ t ];
}
public int Compare( T a, T b )
{
var valueA = GetValue( a );
var valueB = GetValue( b );
if ( valueA != valueB )
{
var difference = valueA - valueB;
if ( reverse_highestFirst )
{
difference = - difference;
}
return MathF.Sign( difference );
}
return 0;
}
public void Sort( List<T> data )
{
ClearCache();
data.Sort( ( a, b ) => Compare( a, b ) );
}
public static void SortList( List<T> data, Func<T,float> getValue )
{
var vc = Create( getValue );
vc.Sort( data );
}
public void Sort( int index, int count, List<T> data )
{
ClearCache();
data.Sort( index, count, Comparer<T>.Create( ( a, b ) => Compare( a, b ) ) );
}
}
}