Protect against index out of range exceptions

This commit is contained in:
Kristian Stolen
2022-01-12 18:09:57 +08:00
parent 84d473d8f2
commit 2a809aabc9
2 changed files with 16 additions and 0 deletions

View File

@@ -37,5 +37,16 @@ namespace Reverse.Tests
Assert.True(input.SequenceEqual(output));
}
[Fact]
public void Reverse_WithIndexGreaterThanArrayLength_DoesNothing()
{
var input = new int[] { 1, 2 };
var output = new int[] { 1, 2 };
Reverser.Reverse(input, input.Length + 1);
Assert.True(input.SequenceEqual(output));
}
}
}

View File

@@ -4,6 +4,11 @@
{
public static void Reverse(int[] arrayToReverse, int indexToReverseTo)
{
if (indexToReverseTo > arrayToReverse.Length)
{
return;
}
for (int i = 0; i < indexToReverseTo / 2; i++)
{
int temp = arrayToReverse[i];