github.com/searKing/golang/go@v1.2.74/container/slice/reduce.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package slice 6 7 import ( 8 "github.com/searKing/golang/go/util/object" 9 "github.com/searKing/golang/go/util/optional" 10 ) 11 12 // ReduceFunc calls a defined callback function on each element of an array, and returns an array that contains the results. 13 func ReduceFunc(s interface{}, f func(left, right interface{}) interface{}) interface{} { 14 return normalizeElem(reduceFunc(Of(s), f), s) 15 } 16 17 // reduceFunc is the same as ReduceFunc 18 func reduceFunc(s []interface{}, f func(left, right interface{}) interface{}, identity ...interface{}) interface{} { 19 object.RequireNonNil(s, "reduceFunc called on nil slice") 20 object.RequireNonNil(f, "reduceFunc called on nil callfn") 21 22 var foundAny bool 23 var result interface{} 24 25 if identity != nil || len(identity) != 0 { 26 foundAny = true 27 result = identity 28 } 29 for _, r := range s { 30 if !foundAny { 31 foundAny = true 32 result = r 33 } else { 34 result = f(result, r) 35 } 36 } 37 if foundAny { 38 return optional.Of(result).Get() 39 } 40 return optional.Empty().Get() 41 }