Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify internal implementation details of EndsWith #1082

Merged
merged 1 commit into from
Sep 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}
}
Loading