-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinject.go
More file actions
40 lines (33 loc) · 964 Bytes
/
inject.go
File metadata and controls
40 lines (33 loc) · 964 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package loncha
// InjectFn ... function for Inject()
type InjectFn[T any, R any] func(R, T) R
// Inject ... return an object formed from operands via InjectFn
func Inject[T any, V any](s []T, injectFn InjectFn[T, V], opts ...OptCurry[V]) (v V) {
if len(opts) > 0 {
p := NewOpt(opts...)
v = p.Default
}
for _, t := range s {
v = injectFn(v, t)
}
return
}
// Reduce ... alias of Inject
func Reduce[T any, V any](s []T, injectFn InjectFn[T, V]) (v V) {
return Inject(s, injectFn)
}
// SumIdent ... return Ordered value onnot-Ordered type
type SumIdent[T any, V Ordered] func(e T) V
// Sum ... sum of slice values in Ordered type
func Sum[T Ordered](s []T) (v T) {
return Inject(s, func(r T, e T) (v T) {
return r + e
})
}
// SumWithFn ... sum of slice values in non-Ordered type with SumIdent()
func SumWithFn[T any, V Ordered](s []T, fn SumIdent[T, V]) (v V) {
return Inject(s, func(result V, e T) V {
v := result + fn(e)
return v
})
}