/src/LinFu.Finders/FuzzyItem.cs

http://github.com/philiplaureano/LinFu · C# · 109 lines · 55 code · 17 blank · 37 comment · 15 complexity · 6f510190a3ee7b35a13d376f3e49dadc MD5 · raw file

  1. using LinFu.Finders.Interfaces;
  2. namespace LinFu.Finders
  3. {
  4. /// <summary>
  5. /// Represents the default implementation of a weighted item in
  6. /// a fuzzy list.
  7. /// </summary>
  8. /// <typeparam name="T">The item type to be tested.</typeparam>
  9. public class FuzzyItem<T> : IFuzzyItem<T>
  10. {
  11. private bool _failed;
  12. private int _matches;
  13. private int _testCount;
  14. /// <summary>
  15. /// Initializes the <see cref="FuzzyItem{T}" /> class with the given <paramref name="item" />.
  16. /// </summary>
  17. /// <param name="item">An instance of the <typeparamref name="T">item type</typeparamref> that will be tested.</param>
  18. public FuzzyItem(T item)
  19. {
  20. Item = item;
  21. _failed = false;
  22. }
  23. /// <summary>
  24. /// Reports the probability of a match
  25. /// based on the <see cref="ICriteria{T}" />
  26. /// that has been tested so far.
  27. /// A value of 1.0 indicates a 100% match;
  28. /// A value of 0.0 equals a zero percent match.
  29. /// </summary>
  30. public double Confidence
  31. {
  32. get
  33. {
  34. if (_failed)
  35. return -1;
  36. double result = 0;
  37. if (_testCount == 0)
  38. return 0;
  39. result = _matches / (double) _testCount;
  40. return result;
  41. }
  42. }
  43. /// <summary>
  44. /// Gets the target item.
  45. /// </summary>
  46. public T Item { get; }
  47. /// <summary>
  48. /// Tests if the current item matches the given
  49. /// <paramref name="criteria" />.
  50. /// </summary>
  51. /// <param name="criteria">
  52. /// The <see cref="ICriteria{T}" /> that determines whether or not the <see cref="Item" /> meets a
  53. /// particular description.
  54. /// </param>
  55. public void Test(ICriteria<T> criteria)
  56. {
  57. // Determine the weight multiplier of this test
  58. var weight = criteria.Weight;
  59. // Ignore any further criteria tests
  60. // if this item fails
  61. if (_failed)
  62. return;
  63. var predicate = criteria.Predicate;
  64. if (predicate == null)
  65. return;
  66. var result = predicate(Item);
  67. // If the critical test fails, all matches will be reset
  68. // to zero and no further matches will be counted
  69. if (result == false && criteria.Type == CriteriaType.Critical)
  70. {
  71. _failed = true;
  72. return;
  73. }
  74. if (result)
  75. _matches += weight;
  76. // Don't count the result if the criteria
  77. // is optional
  78. if (result != true && criteria.Type == CriteriaType.Optional)
  79. return;
  80. _testCount += weight;
  81. }
  82. /// <summary>
  83. /// Resets the item back to its initial state.
  84. /// </summary>
  85. public void Reset()
  86. {
  87. _testCount = 0;
  88. _matches = 0;
  89. _failed = false;
  90. }
  91. }
  92. }