Skip to content

Commit

Permalink
EnumerableUtils.ChunkWhile()
Browse files Browse the repository at this point in the history
  • Loading branch information
Nixill committed Dec 7, 2022
1 parent 5af89a0 commit d951ef3
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
15 changes: 15 additions & 0 deletions CSharp.Nixill.Test/src/NixLibTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Nixill.Objects;
using System.Text.RegularExpressions;
using Nixill.Collections;
using System.Linq;

namespace Nixill.Test {
public class NixLibTests {
Expand Down Expand Up @@ -75,6 +76,20 @@ public void AVLSearchAroundTest() {
TestValues(set.SearchAround(16), 14, 16, 18);
}

[Test]
public void ChunkWhileTest() {
string[] words = EnumerableUtils
.Of('a', 'b', 'c', ' ', 'd', 'e', ' ', 'f')
.ChunkWhile(chr => chr != ' ')
.Select(chunk => chunk.FormString())
.ToArray();

Assert.AreEqual(words.Length, 3);
Assert.AreEqual(words[0], "abc");
Assert.AreEqual(words[1], "de");
Assert.AreEqual(words[2], "f");
}

public void TestValues(NodeTriplet<int> ints, int? lower, int? equal, int? higher) {
if (lower.HasValue) {
Assert.True(ints.HasLesserValue);
Expand Down
22 changes: 22 additions & 0 deletions CSharp.Nixill/src/Utils/EnumerableUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -212,4 +212,26 @@ public static IEnumerable<TSource> MinManyBy<TSource, TResult>(this IEnumerable<
return allItems;
}

public static IEnumerable<IEnumerable<TSource>> ChunkWhile<TSource>(this IEnumerable<TSource> items,
Func<TSource, bool> predicate) {
List<TSource> list = null;

foreach (TSource item in items) {
if (predicate(item)) {
if (list == null) list = new();
list.Add(item);
}
else {
if (list == null) yield return Enumerable.Empty<TSource>();
else {
yield return list;
list = null;
}
}
}

if (list != null) yield return list;
}

public static string FormString(this IEnumerable<char> chars) => new string(chars.ToArray());
}

0 comments on commit d951ef3

Please sign in to comment.