...

Source file src/github.com/thoas/go-funk/operation.go

Documentation: github.com/thoas/go-funk

     1  package funk
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  )
     7  
     8  func calculate(arr interface{}, name string, operation rune) float64 {
     9  	value := redirectValue(reflect.ValueOf(arr))
    10  	valueType := value.Type()
    11  
    12  	kind := value.Kind()
    13  
    14  	if kind == reflect.Array || kind == reflect.Slice {
    15  		length := value.Len()
    16  
    17  		if length == 0 {
    18  			return 0
    19  		}
    20  
    21  		result := map[rune]float64{
    22  			'+': 0.0,
    23  			'*': 1,
    24  		}[operation]
    25  
    26  		for i := 0; i < length; i++ {
    27  			elem := redirectValue(value.Index(i)).Interface()
    28  
    29  			var value float64
    30  			switch e := elem.(type) {
    31  			case int:
    32  				value = float64(e)
    33  			case int8:
    34  				value = float64(e)
    35  			case int16:
    36  				value = float64(e)
    37  			case int32:
    38  				value = float64(e)
    39  			case int64:
    40  				value = float64(e)
    41  			case float32:
    42  				value = float64(e)
    43  			case float64:
    44  				value = e
    45  			}
    46  
    47  			switch operation {
    48  			case '+':
    49  				result += value
    50  			case '*':
    51  				result *= value
    52  			}
    53  		}
    54  
    55  		return result
    56  	}
    57  
    58  	panic(fmt.Sprintf("Type %s is not supported by %s", valueType.String(), name))
    59  }
    60  
    61  // Sum computes the sum of the values in array.
    62  func Sum(arr interface{}) float64 {
    63  	return calculate(arr, "Sum", '+')
    64  }
    65  
    66  // Product computes the product of the values in array.
    67  func Product(arr interface{}) float64 {
    68  	return calculate(arr, "Product", '*')
    69  }
    70  

View as plain text