AbstractCalculator.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. namespace InABox.Avalonia.Converters;
  2. public abstract class AbstractCalculatorFunction<TValue, TType> where TType : struct, IComparable
  3. {
  4. protected abstract TValue Calculate(TValue current, TValue next, TType type) ;
  5. public TValue Calculate(TValue[] value, TType type)
  6. {
  7. if (!value.Any())
  8. return default;
  9. var result = value.First();
  10. result = value.Skip(1).Aggregate(result, (current, next) => Calculate(current, next, type));
  11. return result;
  12. }
  13. }
  14. public abstract class AbstractCalculator<TValue,TFunction, TType> : AbstractMultiConverter<TValue,TValue>
  15. where TFunction : AbstractCalculatorFunction<TValue,TType>, new()
  16. where TType : struct, IComparable
  17. {
  18. public TValue Default { get; private set; }
  19. public TType Type { get; set; }
  20. public TFunction Function { get; private set; }
  21. protected AbstractCalculator()
  22. {
  23. Default = default;
  24. Function = new TFunction();
  25. }
  26. protected override TValue Convert(IEnumerable<TValue> value, object parameter = null)
  27. {
  28. var enumerable = value as TValue[] ?? value?.ToArray() ?? new TValue[] { };
  29. if (Function == null || !enumerable.Any())
  30. return Default;
  31. var result = Function.Calculate(enumerable, Type);
  32. return result;
  33. }
  34. }