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

Add DoWhile operator #242

Merged
merged 1 commit into from
Feb 23, 2023
Merged
Show file tree
Hide file tree
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
42 changes: 42 additions & 0 deletions Source/SuperLinq/DoWhile.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
namespace SuperLinq;

public partial class SuperEnumerable
{
/// <summary>
/// Generates an enumerable sequence by repeating a source sequence as long as the given loop postcondition holds.
/// </summary>
/// <typeparam name="TSource">Source sequence element type.</typeparam>
/// <param name="source">Source sequence to repeat while the condition evaluates true.</param>
/// <param name="condition">Loop condition.</param>
/// <returns>Sequence generated by repeating the given sequence until the condition evaluates to false.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="condition"/> is <see
/// langword="null"/>.</exception>
/// <remarks>
/// <para>
/// <paramref name="condition"/> is evaluated lazily, once at the end of each loop of <paramref name="source"/>.
/// </para>
/// <para>
/// <paramref name="source"/> is cached via <see cref="Memoize{TSource}(IEnumerable{TSource}, bool)"/>, so that it
/// is only iterated once during the first loop. Successive loops will enumerate the cache instead of <paramref
/// name="source"/>.
/// </para>
/// </remarks>
public static IEnumerable<TSource> DoWhile<TSource>(this IEnumerable<TSource> source, Func<bool> condition)
{
Guard.IsNotNull(source);
Guard.IsNotNull(condition);

return Core(source, condition);

static IEnumerable<TSource> Core(IEnumerable<TSource> source, Func<bool> condition)
{
using var memo = source.Memoize();

do
{
foreach (var item in source)
yield return item;
} while (condition());
}
}
}
32 changes: 32 additions & 0 deletions Tests/SuperLinq.Test/DoWhileTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
namespace Test;

public class DoWhileTest
{
[Fact]
public void DoWhileIsLazy()
{
_ = new BreakingSequence<int>().DoWhile(BreakingFunc.Of<bool>());
}

[Fact]
public void DoWhileBehavior()
{
var starts = 0;
var seq = Enumerable.Range(1, 10)
.DoWhile(
() =>
starts++ switch
{
0 or 1 => true,
2 => false,
_ => throw new TestException(),
});

Assert.Equal(0, starts);
seq.AssertSequenceEqual(
Enumerable.Range(1, 10)
.Concat(Enumerable.Range(1, 10))
.Concat(Enumerable.Range(1, 10)));
Assert.Equal(3, starts);
}
}