From 28f8d62a1aefe889bb7444d0ebabf29629b30cb8 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Thu, 25 Apr 2019 11:13:47 -0500 Subject: [PATCH] made methods EnumerableExtensions.CountAtLeast/Most --- .../Extensions/EnumerableExtensions.cs | 22 +++++++++++++++++++ .../utils/Exceptions/ExceptionBuilder.cs | 15 +++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs index 341da0d93..5bc423858 100644 --- a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs @@ -47,6 +47,28 @@ namespace System.Collections.Generic { return rv; } + public static bool CountAtLeast(this IEnumerable source, int count) { + if (count < 0) + throw new ArgumentException(ExceptionBuilder.Format.LessThan(0), nameof(count)); + if (count == 0) + return true; + foreach (var v in source) { + if (--count == 0) + return true; + } + return false; + } + + public static bool CountAtMost(this IEnumerable source, int count) { + if (count < 0) + throw new ArgumentException(ExceptionBuilder.Format.LessThan(0), nameof(count)); + foreach (var v in source) { + if (--count == -1) + return false; + } + return true; + } + public static IEnumerable Convert(this IEnumerable source) { foreach (var v in source) yield return ConvertUtils.try_convert(v); diff --git a/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs b/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs index 68601ed17..bf87ee8af 100644 --- a/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs +++ b/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs @@ -31,5 +31,20 @@ namespace mbts.utils { public static ArgumentOutOfRangeException gte_length(string name) => new ArgumentOutOfRangeException(name, "Index is greater than or equal to the number of elements."); } + + public static class Format { + public static string LessThan(int value) => $"{Messages.LessThan} {value}."; + public static string LessThanOrEqualTo(int value) => $"{Messages.LessThanOrEqualTo} {value}."; + public static string GreaterThan(int value) => $"{Messages.GreaterThan} {value}."; + public static string GreaterThanOrEqualTo(int value) => $"{Messages.GreaterThanOrEqualTo} {value}."; + } + + public static class Messages { + public const string + LessThan = "Less than", + LessThanOrEqualTo = "Less than or equal to", + GreaterThan = "Greater than", + GreaterThanOrEqualTo = "Greater than or equal to"; + } } } \ No newline at end of file