src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

stats.go (988B)


      1 package stats
      2 
      3 import (
      4 	"sort"
      5 	"time"
      6 )
      7 
      8 type DateValue struct {
      9 	Date  time.Time
     10 	Value float64
     11 }
     12 
     13 type Stats struct {
     14 	Values  []DateValue
     15 	Average *float64
     16 	Max     *DateValue
     17 	Median  *float64
     18 	Min     *DateValue
     19 }
     20 
     21 func New(values []DateValue) Stats {
     22 	sort.Slice(values, func(i, j int) bool {
     23 		return values[i].Value < values[j].Value
     24 	})
     25 
     26 	var (
     27 		max *DateValue
     28 		min *DateValue
     29 		sum float64
     30 	)
     31 	for i := range values {
     32 		v := values[i]
     33 
     34 		if max == nil || v.Value >= max.Value {
     35 			max = &v
     36 		}
     37 		if min == nil || v.Value <= min.Value {
     38 			min = &v
     39 		}
     40 
     41 		sum += v.Value
     42 	}
     43 
     44 	var stats = Stats{
     45 		Max:    max,
     46 		Min:    min,
     47 		Values: values,
     48 	}
     49 	if len(values) > 0 {
     50 		avg := sum / float64(len(values))
     51 		stats.Average = &avg
     52 
     53 		middle := len(values) / 2
     54 
     55 		if len(values)%2 != 0 {
     56 			median := values[middle]
     57 
     58 			stats.Median = &median.Value
     59 		} else {
     60 			median := (values[middle-1].Value +
     61 				values[middle].Value) / 2
     62 
     63 			stats.Median = &median
     64 		}
     65 	}
     66 
     67 	return stats
     68 }