77 * Copyright (c) 2025 by Shen, Jen-Chieh $
88 */
99using System ;
10+ using System . Collections . Generic ;
1011
1112namespace JCSUnity
1213{
@@ -21,17 +22,81 @@ public static class JCS_Loop
2122
2223 /* Functions */
2324
25+ /// <summary>
26+ /// Loop in range.
27+ /// </summary>
28+ /// <param name="start"> Start index. </param>
29+ /// <param name="end"> End index. </param>
30+ /// <param name="action"> Action to execute in range. </param>
31+ public static void Range ( int start , int end , Action < int > action )
32+ {
33+ for ( int count = start ; count < end ; ++ count )
34+ {
35+ if ( action != null )
36+ action . Invoke ( count ) ;
37+ }
38+ }
39+
2440 /// <summary>
2541 /// Loops a specific number of times.
2642 /// </summary>
2743 /// <param name="times"> Times to loop over. </param>
2844 /// <param name="action"> Action to execute each times. </param>
2945 public static void Times ( int times , Action < int > action )
3046 {
31- for ( int count = 0 ; count < times ; ++ count )
47+ Range ( 0 , times , action ) ;
48+ }
49+
50+ /// <summary>
51+ /// Like `foreach` but with index.
52+ /// </summary>
53+ /// <typeparam name="T"> The type of the item. </typeparam>
54+ /// <param name="coll"> The collection. </param>
55+ /// <param name="action"> Action to execute. </param>
56+ public static void ForEach < T > ( ICollection < T > coll , Action < T > action )
57+ {
58+ ForEach ( coll , ( count , item ) =>
3259 {
3360 if ( action != null )
34- action . Invoke ( count ) ;
61+ action . Invoke ( item ) ;
62+ } ) ;
63+ }
64+ public static void ForEach < T > ( ICollection < T > coll , Action < int , T > action )
65+ {
66+ int count = 0 ;
67+
68+ foreach ( T item in coll )
69+ {
70+ if ( action != null )
71+ action . Invoke ( count , item ) ;
72+
73+ ++ count ;
74+ }
75+ }
76+
77+ /// <summary>
78+ /// Loop through dictionary.
79+ /// </summary>
80+ /// <param name="dict"> The dictionary. </param>
81+ /// <param name="action"> Action to execute. </param>
82+ public static void ForEach < T , V > ( IDictionary < T , V > dict , Action < KeyValuePair < T , V > > action )
83+ {
84+ ForEach ( dict , ( _ , entry ) =>
85+ {
86+ if ( action != null )
87+ action . Invoke ( entry ) ;
88+ } ) ;
89+ }
90+ public static void ForEach < T , V > ( IDictionary < T , V > dict , Action < int , KeyValuePair < T , V > > action )
91+ {
92+ int count = 0 ;
93+
94+ foreach ( KeyValuePair < T , V > entry in dict )
95+ {
96+ if ( action != null )
97+ action . Invoke ( count , entry ) ;
98+
99+ ++ count ;
35100 }
36101 }
37102 }
0 commit comments