Skip to content

Commit 82ba98b

Browse files
committed
add iterator
1 parent b3b80b1 commit 82ba98b

File tree

3 files changed

+53
-1
lines changed

3 files changed

+53
-1
lines changed

Library/Iterator.cs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
public interface IIterator<T>
2+
{
3+
public T Current { get; }
4+
public bool IsValid();
5+
public IIterator<T> Next();
6+
7+
public static IIterator<T> operator ++(IIterator<T> it) => it.Next();
8+
// public static T operator *(IIterator<T> it) => it.Current;
9+
// public static explicit operator bool(IIterator<T> it) => it.IsValid();
10+
public static bool operator true(IIterator<T> it) => it.IsValid();
11+
public static bool operator false(IIterator<T> it) => !it.IsValid();
12+
};
13+
14+
public class ListIterator<T> : IIterator<T>
15+
{
16+
private int _index = 0;
17+
private List<T> _list;
18+
public ListIterator(List<T> list) => _list = list;
19+
public T Current => _list[_index];
20+
public bool IsValid() => _index >= 0 && _index < _list.Count;
21+
public IIterator<T> Next()
22+
{
23+
_index++;
24+
return this;
25+
}
26+
}
27+
28+
public static class ContainerExtensions
29+
{
30+
public static IIterator<T> GetIterator<T>(this List<T> list)
31+
{
32+
return new ListIterator<T>(list);
33+
}
34+
}

Tests/DependencyInjectorTest/DependencyInjectorTest.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,5 +327,4 @@ public void ShouldGetArrayTypes()
327327
uniqueServices.Should().NotBeNull();
328328
service.Parameters.Should().BeEquivalentTo(uniqueServices);
329329
}
330-
331330
}

Tests/IteratorTest/IteratorTest.cs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
using Library;
2+
3+
namespace Tests.DependencyInjectorTest;
4+
5+
public class IteratorTest
6+
{
7+
[Fact]
8+
public void ShouldIterateOverList()
9+
{
10+
var result = new List<int>();
11+
var list = new List<int> { 1, 2, 3, 4 };
12+
for (var it = list.GetIterator(); it; it++)
13+
{
14+
result.Add(it.Current);
15+
}
16+
17+
result.Should().BeEquivalentTo(new[] { 1, 2, 3, 4 });
18+
}
19+
}

0 commit comments

Comments
 (0)