github.com/kazu/loncha@v0.6.3/inject.go (about) 1 package loncha 2 3 // InjectFn ... function for Inject() 4 type InjectFn[T any, R any] func(R, T) R 5 6 // Inject ... return an object formed from operands via InjectFn 7 func Inject[T any, V any](s []T, injectFn InjectFn[T, V], opts ...OptCurry[V]) (v V) { 8 if len(opts) > 0 { 9 p := NewOpt(opts...) 10 v = p.Default 11 } 12 for _, t := range s { 13 v = injectFn(v, t) 14 } 15 return 16 } 17 18 // Reduce ... alias of Inject 19 func Reduce[T any, V any](s []T, injectFn InjectFn[T, V]) (v V) { 20 return Inject(s, injectFn) 21 } 22 23 // SumIdent ... return Ordered value onnot-Ordered type 24 type SumIdent[T any, V Ordered] func(e T) V 25 26 // Sum ... sum of slice values in Ordered type 27 func Sum[T Ordered](s []T) (v T) { 28 return Inject(s, func(r T, e T) (v T) { 29 return r + e 30 }) 31 32 } 33 34 // SumWithFn ... sum of slice values in non-Ordered type with SumIdent() 35 func SumWithFn[T any, V Ordered](s []T, fn SumIdent[T, V]) (v V) { 36 return Inject(s, func(result V, e T) V { 37 v := result + fn(e) 38 return v 39 }) 40 }