Skip to content

Commit

Permalink
Make array.contains resilient to null values, like array.sort
Browse files Browse the repository at this point in the history
  • Loading branch information
Mertsch committed Dec 23, 2022
1 parent c6ca2f9 commit c0877fd
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Scriban.Tests/TestFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,16 @@ public void TestContains()
Assert.True(ArrayFunctions.Contains(mixed, TestEnum.First));
Assert.True(ArrayFunctions.Contains(mixed, "First"));
Assert.True(ArrayFunctions.Contains(mixed, 100));
Assert.False(ArrayFunctions.Contains(mixed, TestEnum.Second));
Assert.False(ArrayFunctions.Contains(mixed, 101));
Assert.False(ArrayFunctions.Contains(mixed, "Third"));
Assert.False(ArrayFunctions.Contains(null, 1));
TestParser.AssertTemplate("true", "{{ value | array.contains 'First' }}", model: new ObjectModel { Value = mixed });
TestParser.AssertTemplate("true", "{{ value | array.contains 100 }}", model: new ObjectModel { Value = mixed });
TestParser.AssertTemplate("false", "{{ value | array.contains 'Second' }}", model: new ObjectModel { Value = mixed });
TestParser.AssertTemplate("false", "{{ value | array.contains 101 }}", model: new ObjectModel { Value = mixed });
TestParser.AssertTemplate("false", "{{ value | array.contains 'Third' }}", model: new ObjectModel { Value = mixed });
TestParser.AssertTemplate("false", "{{ null | array.contains 100 }}");
}
class ObjectModel
{
Expand Down
5 changes: 5 additions & 0 deletions src/Scriban/Functions/ArrayFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -668,6 +668,11 @@ public static IEnumerable Uniq(IEnumerable list)
/// </remarks>
public static bool Contains(IEnumerable list, object item)
{
if (list == null)
{
return false;
}

foreach (var element in list)
{
if (element == item || (element != null && element.Equals(item))) return true;
Expand Down

0 comments on commit c0877fd

Please sign in to comment.