AbstractCalculator.cs 1.6 KB

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