From 85becd241533fccf8ec534a41fd148168cd59f9c Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 20 Apr 2022 19:27:06 +0100 Subject: [PATCH] Add Array.Fill --- X10D.Tests/src/Core/ArrayTests.cs | 23 +++++++++- X10D/src/ArrayExtensions/ArrayExtensions.cs | 49 ++++++++++++++++++++- 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/X10D.Tests/src/Core/ArrayTests.cs b/X10D.Tests/src/Core/ArrayTests.cs index 3b12420..8bd6533 100644 --- a/X10D.Tests/src/Core/ArrayTests.cs +++ b/X10D.Tests/src/Core/ArrayTests.cs @@ -15,8 +15,7 @@ public class ArrayTests args.Clear(); int[] comparison = Enumerable.Repeat(0, args.Length).ToArray(); - CollectionAssert.AreEqual(args, comparison, $"{string.Join(", ", args)} is not equal to" + - $"{string.Join(", ", comparison)}. "); + CollectionAssert.AreEqual(args, comparison); } [TestMethod] @@ -25,4 +24,24 @@ public class ArrayTests int[]? array = null; Assert.ThrowsException(array!.Clear); } + + [TestMethod] + [DataRow] + [DataRow(1)] + [DataRow(1, 2, 3)] + [DataRow(1, 2, 3, 4, 5)] + public void Fill(params int[] args) + { + args.Fill(1); + + int[] comparison = Enumerable.Repeat(1, args.Length).ToArray(); + CollectionAssert.AreEqual(args, comparison); + } + + [TestMethod] + public void FillNull() + { + int[]? array = null; + Assert.ThrowsException(() => array!.Fill(0)); + } } diff --git a/X10D/src/ArrayExtensions/ArrayExtensions.cs b/X10D/src/ArrayExtensions/ArrayExtensions.cs index 6f454dc..8968adc 100644 --- a/X10D/src/ArrayExtensions/ArrayExtensions.cs +++ b/X10D/src/ArrayExtensions/ArrayExtensions.cs @@ -53,7 +53,7 @@ public static class ArrayExtensions { end = array.Length - end; } - + array.Clear(index, end - index); } @@ -86,4 +86,51 @@ public static class ArrayExtensions Array.Clear(array, index, length); } + + /// + /// Assigns the given value to each element of the array. + /// + /// The array to be filled. + /// The value to assign to each array element. + /// The type of the elements in the array. + /// is . + public static void Fill(this T?[] array, T value) + { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + + if (array.Length == 0) + { + return; + } + + Array.Fill(array, value); + } + + /// + /// Assigns the given value to the elements of the array which are within the range of + /// (inclusive) and the next number of indices. + /// + /// The array to be filled. + /// The value to assign to each array element. + /// A 32-bit integer that represents the index in the array at which filling begins. + /// The number of elements to fill. + /// The type of the elements in the array. + /// is . + public static void Fill(this T?[] array, T value, int startIndex, int count) + { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + + if (count == 0 || array.Length == 0) + { + return; + } + + Array.Fill(array, value, startIndex, count); + } }