@@ -11,14 +11,23 @@ internal sealed class LazyList<[DynamicallyAccessedMembers(DynamicallyAccessedMe
1111 where T : class
1212{
1313 internal readonly T [ ] _items ;
14- internal readonly Func < int , T > _valueFactory ;
14+ internal readonly Func < int , T > ? _valueFactory ;
15+ internal readonly Func < int , T ? , T > ? _valueFactoryWithPreviousValue ;
1516
1617 public static readonly LazyList < T > Empty = new LazyList < T > ( 0 , _ => null ! ) ;
1718
1819 public LazyList ( int count , Func < int , T > valueFactory )
1920 {
2021 _items = ( count <= 0 ) ? [ ] : new T [ count ] ;
2122 _valueFactory = valueFactory ;
23+ _valueFactoryWithPreviousValue = null ;
24+ }
25+
26+ public LazyList ( int count , Func < int , T ? , T > valueFactoryWithPreviousValue )
27+ {
28+ _items = ( count <= 0 ) ? [ ] : new T [ count ] ;
29+ _valueFactory = null ;
30+ _valueFactoryWithPreviousValue = valueFactoryWithPreviousValue ;
2231 }
2332
2433 public T this [ int index ]
@@ -30,7 +39,14 @@ public T this[int index]
3039
3140 if ( item is null )
3241 {
33- item = _valueFactory ( index ) ;
42+ if ( _valueFactoryWithPreviousValue is not null )
43+ {
44+ item = _valueFactoryWithPreviousValue ( index , index == 0 ? null : _items [ index - 1 ] ) ;
45+ }
46+ else
47+ {
48+ item = _valueFactory ! . Invoke ( index ) ;
49+ }
3450 items [ index ] = item ;
3551 }
3652
@@ -56,14 +72,7 @@ public void CopyTo(T[] array, int arrayIndex)
5672
5773 for ( var i = 0 ; i < items . Length ; i ++ )
5874 {
59- var currentItem = items [ i ] ;
60-
61- if ( currentItem is null )
62- {
63- currentItem = _valueFactory ( i ) ;
64- items [ i ] = currentItem ;
65- }
66-
75+ var currentItem = this [ i ] ;
6776 array [ arrayIndex + i ] = currentItem ;
6877 }
6978 }
@@ -76,14 +85,7 @@ public int IndexOf(T item)
7685
7786 for ( var i = 0 ; i < items . Length ; i ++ )
7887 {
79- var currentItem = items [ i ] ;
80-
81- if ( currentItem is null )
82- {
83- currentItem = _valueFactory ( i ) ;
84- items [ i ] = currentItem ;
85- }
86-
88+ var currentItem = this [ i ] ;
8789 if ( EqualityComparer < T > . Default . Equals ( currentItem , item ) )
8890 {
8991 return i ;
0 commit comments