Skip to content

Commit

Permalink
feat: add reduce func
Browse files Browse the repository at this point in the history
  • Loading branch information
romain-jeannoutot committed Oct 25, 2022
1 parent d07db06 commit 4d69445
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
6 changes: 6 additions & 0 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,10 @@ func main() {

// false
log.Println(goslices.Some(users, NewFirstnameSpecification("Mike")))

// map[Aliyah:1 Arnas:1 John:2 Marcos:1]
log.Println(goslices.Reduce(users, func(acc map[string]int, user User, _ int, _ []User) map[string]int {
acc[user.firstname]++
return acc
}, map[string]int{}))
}
10 changes: 10 additions & 0 deletions reduce.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package goslices

func Reduce[T any, S any](items []T, callback func(acc S, item T, idx int, items []T) S, initialValue S) S {
s := initialValue
for idx, item := range items {
s = callback(s, item, idx, items)
}

return s
}

0 comments on commit 4d69445

Please sign in to comment.