Skip to content

Commit

Permalink
Simplify internal implementation details of "EndsWith"
Browse files Browse the repository at this point in the history
  • Loading branch information
atifaziz committed Sep 22, 2024
1 parent 5dc9e18 commit e52d278
Showing 1 changed file with 5 additions and 13 deletions.
18 changes: 5 additions & 13 deletions MoreLinq/EndsWith.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,22 +71,14 @@ public static bool EndsWith<T>(this IEnumerable<T> first, IEnumerable<T> second,
if (first == null) throw new ArgumentNullException(nameof(first));
if (second == null) throw new ArgumentNullException(nameof(second));

comparer ??= EqualityComparer<T>.Default;

List<T> secondList;
#pragma warning disable IDE0075 // Simplify conditional expression (makes it worse)
return second.TryAsCollectionLike() is { Count: var secondCount }
? first.TryAsCollectionLike() is { Count: var firstCount } && secondCount > firstCount
? false
: Impl(first, second, secondCount, comparer)
: Impl(first, secondList = second.ToList(), secondList.Count, comparer);
#pragma warning restore IDE0075 // Simplify conditional expression
? first.TryAsCollectionLike() is not { Count: var firstCount } || secondCount <= firstCount
&& EndsWith(second, secondCount)
: EndsWith(secondList = second.ToList(), secondList.Count);

static bool Impl(IEnumerable<T> first, IEnumerable<T> second, int count, IEqualityComparer<T> comparer)
{
using var firstIter = first.TakeLast(count).GetEnumerator();
return second.All(item => firstIter.MoveNext() && comparer.Equals(firstIter.Current, item));
}
bool EndsWith(IEnumerable<T> second, int count) =>
first.TakeLast(count).SequenceEqual(second, comparer);
}
}
}

0 comments on commit e52d278

Please sign in to comment.