Skip to content

Commit

Permalink
Implement output sorting by observation fields
Browse files Browse the repository at this point in the history
  • Loading branch information
msharris committed Mar 15, 2024
1 parent e621e06 commit becd883
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 3 deletions.
77 changes: 76 additions & 1 deletion app/app.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package app

import (
"errors"
"fmt"
"slices"
"strings"
Expand All @@ -9,10 +10,44 @@ import (

type Options struct {
Locations []string
Sort string
Sort Field
Reverse bool
}

type Field string

const (
Id Field = "id"
Name Field = "name"
UVIndex Field = "index"
Time Field = "time"
Available Field = "status"
)

// Implement pflag.Value interface on Field for Cobra
func (f *Field) String() string {
return string(*f)
}

func (f *Field) Set(s string) error {
s = strings.ToLower(s)
switch s {
case "id", "name", "index", "time", "status":
*f = Field(s)
case "uv":
*f = UVIndex
case "date":
*f = Time
default:
return errors.New(`must be one of "id", "name", "index", "uv", "time", "date", "status"`)
}
return nil
}

func (f *Field) Type() string {
return "field"
}

type Station struct {
Id string
Name string
Expand All @@ -35,6 +70,8 @@ func Run(options Options) error {
stations = filter(stations, options.Locations)
}

sort(stations, options.Sort)

if options.Reverse {
slices.Reverse(stations)
}
Expand All @@ -59,3 +96,41 @@ func filter(stations []Station, names []string) []Station {
}
return filtered
}

func sort(stations []Station, f Field) {
switch f {
case Id:
slices.SortFunc(stations, func(s1, s2 Station) int {
return strings.Compare(s1.Id, s2.Id)
})
case Name:
slices.SortFunc(stations, func(s1, s2 Station) int {
return strings.Compare(s1.Name, s2.Name)
})
case UVIndex:
slices.SortFunc(stations, func(s1, s2 Station) int {
if s1.UVIndex < s2.UVIndex {
return -1
} else if s1.UVIndex > s2.UVIndex {
return 1
} else {
return 0
}
})
case Time:
slices.SortFunc(stations, func(s1, s2 Station) int {
return s1.Time.Compare(s2.Time)
})
case Available:
slices.SortFunc(stations, func(s1, s2 Station) int {
a1, a2 := 0, 0
if s1.Available {
a1 = 1
}
if s2.Available {
a2 = 1
}
return a1 - a2
})
}
}
4 changes: 2 additions & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ func Execute() {
}
}

var flags = app.Options{}
var flags = app.Options{Sort: app.Name}

func init() {
rootCmd.Flags().StringSliceVarP(&flags.Locations, "locations", "l", nil, "a comma-separated list of locations to display")
//rootCmd.Flags().StringVarP(&flags.Sort, "sort", "s", "name", "field to sort the observations by")
rootCmd.Flags().VarP(&flags.Sort, "sort", "s", "field to sort the observations by")
rootCmd.Flags().BoolVarP(&flags.Reverse, "reverse", "r", false, "print the observations in reverse order")
}

0 comments on commit becd883

Please sign in to comment.