// Copyright © WireMock.Net
using WireMock.Types;
namespace WireMock.Matchers;
///
/// MatchScores
///
public static class MatchScores
{
///
/// The tolerance
///
public const double Tolerance = 0.000001;
///
/// The default mismatch score
///
public const double Mismatch = 0.0;
///
/// The default perfect match score
///
public const double Perfect = 1.0;
///
/// The almost perfect match score
///
public const double AlmostPerfect = 0.99;
///
/// Is the value a perfect match?
///
/// The value.
/// true/false
public static bool IsPerfect(double value)
{
return Math.Abs(value - Perfect) < Tolerance;
}
///
/// Convert a bool to the score.
///
/// if set to true [value].
/// score
public static double ToScore(bool value)
{
return value ? Perfect : Mismatch;
}
///
/// Calculates the score from multiple values.
///
/// The values.
/// The .
/// average score
public static double ToScore(IReadOnlyList values, MatchOperator matchOperator)
{
return ToScore(values.Select(ToScore).ToArray(), matchOperator);
}
///
/// Calculates the score from multiple values.
///
/// The values.
///
/// average score
public static double ToScore(IReadOnlyList values, MatchOperator matchOperator)
{
if (values.Count == 0)
{
return Mismatch;
}
return matchOperator switch
{
MatchOperator.Or => ToScore(values.Any(IsPerfect)),
MatchOperator.And => ToScore(values.All(IsPerfect)),
_ => values.Average()
};
}
internal static double ToScore(WireMockList values, IStringMatcher[] matchers, MatchOperator matchOperator = MatchOperator.And)
{
// Create a matrix of scores where each row corresponds to a value and each column corresponds to a matcher.
var matrix = values
.Select(value => matchers
.Select(matcher => matcher.IsMatch(value).Score).ToArray()
)
.ToArray();
if (matrix.Length == 0 || matchers.Length == 0)
{
return Mismatch;
}
// For each value, how well was it matched by its best matcher?
var rowScore = matchOperator == MatchOperator.And ? matrix.Average(row => row.Max()) : matrix.Max(row => row.Max());
// For each matcher, how well was it satisfied by its best value?
var columnRange = Enumerable.Range(0, matchers.Length);
var columnScore = matchOperator == MatchOperator.And ? columnRange.Average(column => matrix.Max(row => row[column])) : columnRange.Max(column => matrix.Max(row => row[column]));
return matchOperator == MatchOperator.And ? Math.Min(rowScore, columnScore) : Math.Max(rowScore, columnScore);
}
}