Skip to content

Commit

Permalink
DYN-6985 Get item from list with negative index (Wishlist #187) (#15205)
Browse files Browse the repository at this point in the history
Co-authored-by: Aaron (Qilong) <[email protected]>
  • Loading branch information
tinrobot2000 and QilongTang authored May 28, 2024
1 parent 3e1c0ad commit 1f062c7
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Libraries/CoreNodes/List.cs
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,16 @@ public static IList ShiftIndices(IList list, int amount)
[IsVisibleInDynamoLibrary(true)]
public static object GetItemAtIndex(IList list, int index)
{
if (index<0)
{
index = list.Count + index;
}

// When calculated index is more than list count or still negative, throw exception
if (index >= list.Count || index < 0)
{
throw new IndexOutOfRangeException();
}
return list[index];
}

Expand Down
30 changes: 30 additions & 0 deletions test/Libraries/CoreNodesTests/ListTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Dynamo.Graph.Nodes;
using NUnit.Framework;
using List = DSCore.List;

Expand Down Expand Up @@ -500,6 +501,35 @@ public static void GetFromList()
Assert.AreEqual(2, List.GetItemAtIndex(new List<int> { 0, 1, 2, 3 }, 2));
}

[Test]
[Category("UnitTests")]
public static void GetNegtiveIndexItemFromList()
{
Assert.AreEqual(3, List.GetItemAtIndex(new List<int> { 0, 1, 2, 3 }, -1));
}

[Test]
[Category("UnitTests")]
public static void GetNegtiveIndexItemFromListCouldThrow()
{
Assert.Throws<IndexOutOfRangeException>(() =>
{
// -7 as index argument will cause exception.
List.GetItemAtIndex(new List<int> { 0, 1, 2, 3 }, -7);
});
}

[Test]
[Category("UnitTests")]
public static void GetPositiveIndexItemFromListCouldThrow()
{
Assert.Throws<IndexOutOfRangeException>(() =>
{
// 7 as index argument will cause exception.
List.GetItemAtIndex(new List<int> { 0, 1, 2, 3 }, 7);
});
}

[Test]
[Category("UnitTests")]
public static void TakeListSlice()
Expand Down

0 comments on commit 1f062c7

Please sign in to comment.