From d951ef3c038c03e3de4369395587e356a4a4d3a1 Mon Sep 17 00:00:00 2001 From: Steven Date: Wed, 7 Dec 2022 04:15:55 -0500 Subject: [PATCH] EnumerableUtils.ChunkWhile() --- CSharp.Nixill.Test/src/NixLibTests.cs | 15 +++++++++++++++ CSharp.Nixill/src/Utils/EnumerableUtils.cs | 22 ++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/CSharp.Nixill.Test/src/NixLibTests.cs b/CSharp.Nixill.Test/src/NixLibTests.cs index 1d5e525..9059fc5 100644 --- a/CSharp.Nixill.Test/src/NixLibTests.cs +++ b/CSharp.Nixill.Test/src/NixLibTests.cs @@ -4,6 +4,7 @@ using Nixill.Objects; using System.Text.RegularExpressions; using Nixill.Collections; +using System.Linq; namespace Nixill.Test { public class NixLibTests { @@ -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 ints, int? lower, int? equal, int? higher) { if (lower.HasValue) { Assert.True(ints.HasLesserValue); diff --git a/CSharp.Nixill/src/Utils/EnumerableUtils.cs b/CSharp.Nixill/src/Utils/EnumerableUtils.cs index 5d25d40..0534a07 100644 --- a/CSharp.Nixill/src/Utils/EnumerableUtils.cs +++ b/CSharp.Nixill/src/Utils/EnumerableUtils.cs @@ -212,4 +212,26 @@ public static IEnumerable MinManyBy(this IEnumerable< return allItems; } + public static IEnumerable> ChunkWhile(this IEnumerable items, + Func predicate) { + List 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(); + else { + yield return list; + list = null; + } + } + } + + if (list != null) yield return list; + } + + public static string FormString(this IEnumerable chars) => new string(chars.ToArray()); } \ No newline at end of file