diff --git a/X10D.Tests/src/Core/CoreTests.cs b/X10D.Tests/src/Core/CoreTests.cs index 1da56e1..57bf03d 100644 --- a/X10D.Tests/src/Core/CoreTests.cs +++ b/X10D.Tests/src/Core/CoreTests.cs @@ -1,4 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.VisualStudio.TestTools.UnitTesting; using X10D.Core; namespace X10D.Tests.Core; @@ -49,5 +49,28 @@ public class CoreTests Assert.IsNotNull(enumerable); Assert.AreEqual(o, enumerable.ElementAt(0)); } + + [TestMethod] + [DataRow(1)] + [DataRow("f")] + [DataRow(true)] + public void RepeatValue_ShouldContainRepeatedValue_GivenValue(object o) + { + IEnumerable enumerable = o.RepeatValue(10); + Assert.IsNotNull(enumerable); + + object[] array = enumerable.ToArray(); + Assert.AreEqual(10, array.Length); + CollectionAssert.AreEqual(new[] {o, o, o, o, o, o, o, o, o, o}, array); + } + + [TestMethod] + [DataRow(1)] + [DataRow("f")] + [DataRow(true)] + public void RepeatValue_ShouldThrow_GivenNegativeCount(object o) + { + // we must force enumeration via ToArray() to ensure the exception is thrown + Assert.ThrowsException(() => o.RepeatValue(-1).ToArray()); } } diff --git a/X10D/src/Core/Extensions.cs b/X10D/src/Core/Extensions.cs index 0dec423..2498eff 100644 --- a/X10D/src/Core/Extensions.cs +++ b/X10D/src/Core/Extensions.cs @@ -1,4 +1,4 @@ -namespace X10D.Core; +namespace X10D.Core; /// /// Extension methods which apply to all types. @@ -30,4 +30,25 @@ public static class Extensions { yield return value; } + + /// + /// Returns an enumerable collection containing the current value repeated a specified number of times. + /// + /// The value to repeat. + /// The number of times to repeat . + /// The type of . + /// An enumerable collection containing repeated times. + /// is less than 0. + public static IEnumerable RepeatValue(this T value, int count) + { + if (count < 0) + { + throw new ArgumentOutOfRangeException(nameof(count), ExceptionMessages.CountMustBeGreaterThanOrEqualTo0); + } + + for (var i = 0; i < count; i++) + { + yield return value; + } + } }