Add docs and unit tests for `IList.LowerBoundBinarySearch` extension
without d29da10e9
, the final case in this test method would throw an exception
This commit is contained in:
parent
49fa40f562
commit
2f758459dd
|
@ -17,6 +17,14 @@ namespace BizHawk.Common.CollectionExtensions
|
|||
return desc ? source.OrderByDescending(keySelector) : source.OrderBy(keySelector);
|
||||
}
|
||||
|
||||
/// <summary>Implements an indirected binary search.</summary>
|
||||
/// <return>
|
||||
/// The index of the element whose key matches <paramref name="key"/>;
|
||||
/// or if none match, the index of the element whose key is closest and lower;
|
||||
/// or if all elements' keys are higher, <c>-1</c>.<br/>
|
||||
/// (Equivalently: If none match, 1 less than the index where inserting an element with the given <paramref name="key"/> would keep the list sorted)
|
||||
/// </return>
|
||||
/// <remarks>The returned index may not be accurate if <paramref name="list"/> is not sorted in ascending order with respect to <paramref name="keySelector"/>.</remarks>
|
||||
public static int LowerBoundBinarySearch<T, TKey>(this IList<T> list, Func<T, TKey> keySelector, TKey key)
|
||||
where TKey : IComparable<TKey>
|
||||
{
|
||||
|
|
|
@ -75,6 +75,18 @@ namespace BizHawk.Tests.Common.CollectionExtensions
|
|||
Assert.AreEqual(0, Array.Empty<int>().ConcatArray(Array.Empty<int>()).Length);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TestLowerBoundBinarySearch()
|
||||
{
|
||||
List<string> a = new(new[] { "a", "abc", "abcde", "abcdef", "abcdefg" });
|
||||
Assert.AreEqual(-1, a.LowerBoundBinarySearch(static s => s.Length, 0), "length 0");
|
||||
Assert.AreEqual(0, a.LowerBoundBinarySearch(static s => s.Length, 1), "length 1");
|
||||
Assert.AreEqual(1, a.LowerBoundBinarySearch(static s => s.Length, 4), "length 4");
|
||||
Assert.AreEqual(2, a.LowerBoundBinarySearch(static s => s.Length, 5), "length 5");
|
||||
Assert.AreEqual(4, a.LowerBoundBinarySearch(static s => s.Length, 7), "length 7");
|
||||
Assert.AreEqual(4, a.LowerBoundBinarySearch(static s => s.Length, 8), "length 8");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TestRemoveAll()
|
||||
{
|
||||
|
|
Loading…
Reference in New Issue