| 1 |
// Copyright 2011 The Go Authors. |
| 2 |
// Copyright 2015 Randall Farmer. |
| 3 |
// All rights reserved. |
| 4 |
// Use of this source code is governed by a BSD-style |
| 5 |
// license that can be found in the LICENSE file. |
| 6 |
|
| 7 |
package sorts_test |
| 8 |
|
| 9 |
import ( |
| 10 |
"fmt" |
| 11 |
"github.com/twotwotwo/sorts" |
| 12 |
"github.com/twotwotwo/sorts/sortutil" |
| 13 |
) |
| 14 |
|
| 15 |
type City struct { |
| 16 |
Name string |
| 17 |
Latitude, Longitude float32 |
| 18 |
} |
| 19 |
|
| 20 |
func (c City) String() string { return fmt.Sprintf("%s (%.1f, %.1f)", c.Name, c.Latitude, c.Longitude) } |
| 21 |
|
| 22 |
// ByLatitude implements sort.Interface for []City based on |
| 23 |
// the Latitude field, for sorting cities south to north. |
| 24 |
type ByLatitude []City |
| 25 |
|
| 26 |
func (a ByLatitude) Len() int { return len(a) } |
| 27 |
func (a ByLatitude) Swap(i, j int) { a[i], a[j] = a[j], a[i] } |
| 28 |
|
| 29 |
// Float32Key and Float32Less make the sort handle the sign bit and sort NaN |
| 30 |
// values to the end. There are also Float64Key and Float64Less, and |
| 31 |
// [Type]Key functions for int types. |
| 32 |
|
| 33 |
// Key returns a uint64 that is lower for more southerly latitudes. |
| 34 |
func (a ByLatitude) Key(i int) uint64 { |
| 35 |
return sortutil.Float32Key(a[i].Latitude) |
| 36 |
} |
| 37 |
func (a ByLatitude) Less(i, j int) bool { |
| 38 |
return sortutil.Float32Less(a[i].Latitude, a[j].Latitude) |
| 39 |
} |
| 40 |
|
| 41 |
func Example() { |
| 42 |
cities := []City{ |
| 43 |
{"Vancouver", 49.3, -123.1}, |
| 44 |
{"Tokyo", 35.6, 139.7}, |
| 45 |
{"Honolulu", 21.3, -157.8}, |
| 46 |
{"Sydney", -33.9, 151.2}, |
| 47 |
} |
| 48 |
|
| 49 |
fmt.Println(cities) |
| 50 |
sorts.ByUint64(ByLatitude(cities)) |
| 51 |
fmt.Println(cities) |
| 52 |
|
| 53 |
// Output: |
| 54 |
// [Vancouver (49.3, -123.1) Tokyo (35.6, 139.7) Honolulu (21.3, -157.8) Sydney (-33.9, 151.2)] |
| 55 |
// [Sydney (-33.9, 151.2) Honolulu (21.3, -157.8) Tokyo (35.6, 139.7) Vancouver (49.3, -123.1)] |
| 56 |
} |