From 1f062c741143470e128761fd64d58144b99ed92f Mon Sep 17 00:00:00 2001 From: Mike <17667690+tinrobot2000@users.noreply.github.com> Date: Wed, 29 May 2024 03:04:59 +0800 Subject: [PATCH] DYN-6985 Get item from list with negative index (Wishlist #187) (#15205) Co-authored-by: Aaron (Qilong) --- src/Libraries/CoreNodes/List.cs | 10 ++++++++ test/Libraries/CoreNodesTests/ListTests.cs | 30 ++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/Libraries/CoreNodes/List.cs b/src/Libraries/CoreNodes/List.cs index 0288c0b7e03..4833971c456 100644 --- a/src/Libraries/CoreNodes/List.cs +++ b/src/Libraries/CoreNodes/List.cs @@ -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]; } diff --git a/test/Libraries/CoreNodesTests/ListTests.cs b/test/Libraries/CoreNodesTests/ListTests.cs index 59e2c24bbf0..14c2fbd110e 100644 --- a/test/Libraries/CoreNodesTests/ListTests.cs +++ b/test/Libraries/CoreNodesTests/ListTests.cs @@ -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; @@ -500,6 +501,35 @@ public static void GetFromList() Assert.AreEqual(2, List.GetItemAtIndex(new List { 0, 1, 2, 3 }, 2)); } + [Test] + [Category("UnitTests")] + public static void GetNegtiveIndexItemFromList() + { + Assert.AreEqual(3, List.GetItemAtIndex(new List { 0, 1, 2, 3 }, -1)); + } + + [Test] + [Category("UnitTests")] + public static void GetNegtiveIndexItemFromListCouldThrow() + { + Assert.Throws(() => + { + // -7 as index argument will cause exception. + List.GetItemAtIndex(new List { 0, 1, 2, 3 }, -7); + }); + } + + [Test] + [Category("UnitTests")] + public static void GetPositiveIndexItemFromListCouldThrow() + { + Assert.Throws(() => + { + // 7 as index argument will cause exception. + List.GetItemAtIndex(new List { 0, 1, 2, 3 }, 7); + }); + } + [Test] [Category("UnitTests")] public static void TakeListSlice()