namespace Wrapped;
/// Our own LINQ-like operators, written as iterator methods.
public static class EnumerableExtensions
{
/// Returns the elements satisfying the predicate (our own Where).
public static IEnumerable Filter(this IEnumerable source, Func predicate)
{
foreach (var item in source)
{
if (predicate(item))
{
yield return item;
}
}
}
/// Transforms every element (our own Select).
public static IEnumerable Map(this IEnumerable source, Func selector)
{
foreach (var item in source)
{
yield return selector(item);
}
}
/// Calls the action for every element passing through - handy for logging.
public static IEnumerable Tap(this IEnumerable source, Action action)
{
foreach (var item in source)
{
action(item);
yield return item;
}
}
/// Returns pairs of consecutive elements: (a, b), (b, c), (c, d), ...
public static IEnumerable<(T Previous, T Current)> Pairwise(this IEnumerable source)
{
using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext())
{
yield break;
}
T previous = enumerator.Current;
while (enumerator.MoveNext())
{
yield return (previous, enumerator.Current);
previous = enumerator.Current;
}
}
///
/// Splits the sequence into consecutive groups. A new group starts whenever
/// returns true for a pair of neighbouring elements.
///
public static IEnumerable> SplitWhen(this IEnumerable source, Func startsNewGroup)
{
List group = [];
foreach (var item in source)
{
if (group.Count > 0 && startsNewGroup(group[^1], item))
{
yield return group;
group = [];
}
group.Add(item);
}
if (group.Count > 0)
{
yield return group;
}
}
}