File tree Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Original file line number Diff line number Diff line change @@ -60,3 +60,14 @@ func ToChannel[T any](iter Iterator[T]) chan T {
6060
6161 return ch
6262}
63+
64+ // ForEach consumes an iterator and executes callback function on each item.
65+ func ForEach [T any ](iter Iterator [T ], callback func (T )) {
66+ for {
67+ if value , ok := iter .Next ().Value (); ok {
68+ callback (value )
69+ } else {
70+ break
71+ }
72+ }
73+ }
Original file line number Diff line number Diff line change @@ -70,3 +70,22 @@ func TestToChannelEmpty(t *testing.T) {
7070 t .Fail ()
7171 }
7272}
73+
74+ func TestForEach (t * testing.T ) {
75+ words := iter .Lift ([]string {"foo" , "bar" , "baz" })
76+ sum := ""
77+ iter .ForEach [string ](words , func (word string ) {
78+ sum += word
79+ })
80+ assert .Equal (t , "foobarbaz" , sum )
81+ }
82+
83+ func TestForEachEmpty (t * testing.T ) {
84+ words := iter .Lift ([]string {})
85+ sum := ""
86+ iter .ForEach [string ](words , func (word string ) {
87+ sum += word
88+ })
89+
90+ assert .Empty [string ](t , sum )
91+ }
You can’t perform that action at this time.
0 commit comments