Add T.RepeatValue(int)

This commit is contained in:
Oliver Booth 2022-04-29 11:16:44 +01:00
parent d80367c00c
commit dc3de3816e
No known key found for this signature in database
GPG Key ID: 32A00B35503AF634
2 changed files with 46 additions and 2 deletions

View File

@ -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<object> 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<ArgumentOutOfRangeException>(() => o.RepeatValue(-1).ToArray());
}
}

View File

@ -1,4 +1,4 @@
namespace X10D.Core;
namespace X10D.Core;
/// <summary>
/// Extension methods which apply to all types.
@ -30,4 +30,25 @@ public static class Extensions
{
yield return value;
}
/// <summary>
/// Returns an enumerable collection containing the current value repeated a specified number of times.
/// </summary>
/// <param name="value">The value to repeat.</param>
/// <param name="count">The number of times to repeat <paramref name="value" />.</param>
/// <typeparam name="T">The type of <paramref name="value"/>.</typeparam>
/// <returns>An enumerable collection containing <paramref name="value" /> repeated <paramref name="count" /> times.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="count" /> is less than 0.</exception>
public static IEnumerable<T> RepeatValue<T>(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;
}
}
}