Skip to content

Commit

Permalink
Merge pull request #488 from DenisPimenov/compact-list-contains
Browse files Browse the repository at this point in the history
Add Contains and IndexOf methods for consistency with System.Collections.Generic.List<>
  • Loading branch information
ulex authored Jul 30, 2024
2 parents a2646dc + 433f434 commit 396da37
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
21 changes: 21 additions & 0 deletions rd-net/Lifetimes/Collections/CompactList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,27 @@ public void Clear()
myMultipleValues = null;
}

public bool Contains(T item, IEqualityComparer<T?> comparer)
{
return IndexOf(item, comparer) >= 0;
}

public int IndexOf(T item, IEqualityComparer<T?> comparer)
{
switch (Count)
{
case 0: return -1;
case 1: return comparer.Equals(mySingleValue, item) ? 0 : -1;
default:
Assertion.AssertNotNull(myMultipleValues);
for (var i = 0; i < myMultipleValues.Count; i++)
{
if (comparer.Equals(myMultipleValues[i], item)) return i;
}
return -1;
}
}

public int LastIndexOf(T item, IEqualityComparer<T?> comparer)
{
switch (Count)
Expand Down
42 changes: 42 additions & 0 deletions rd-net/Test.Lifetimes/Collections/CompactListTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System.Collections.Generic;
using JetBrains.Collections;
using NUnit.Framework;

namespace Test.Lifetimes.Collections
{
[TestFixture]
public class CompactListTest
{
[TestCase(new int[0], 1, false)]
[TestCase(new[] { 1 }, 1, true)]
[TestCase(new[] { 1 }, 2, false)]
[TestCase(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 5, true)]
[TestCase(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 0, false)]
public void TestContains(int[] values, int value, bool expected)
{
var compactList = new CompactList<int>();
for (int i = 0; i < values.Length; i++)
{
compactList.Add(values[i]);
}

Assert.AreEqual(compactList.Contains(value, EqualityComparer<int>.Default), expected);
}

[TestCase(new int[0], 1, -1)]
[TestCase(new[] { 1 }, 1, 0)]
[TestCase(new[] { 1 }, 2, -1)]
[TestCase(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 5, 4)]
[TestCase(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 0, -1)]
public void TestIndexOf(int[] values, int value, int expectedIndex)
{
var compactList = new CompactList<int>();
for (int i = 0; i < values.Length; i++)
{
compactList.Add(values[i]);
}

Assert.AreEqual(compactList.IndexOf(value, EqualityComparer<int>.Default), expectedIndex);
}
}
}

0 comments on commit 396da37

Please sign in to comment.