-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort.go
More file actions
82 lines (68 loc) · 1.88 KB
/
sort.go
File metadata and controls
82 lines (68 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright © 2025 Pennock Tech, LLC.
// All rights reserved, except as granted under license.
// Licensed per file LICENSE.txt
package tabular // import "go.pennock.tech/tabular"
import (
"errors"
"sort"
"strconv"
)
type ErrorNoSuchColumn string
func (e ErrorNoSuchColumn) Error() string { return "no such column " + strconv.Quote(string(e)) }
type ErrorColumnOutOfRange int
func (e ErrorColumnOutOfRange) Error() string {
return "column " + strconv.Itoa(int(e)) + " out of range"
}
var ErrNoColumnHeaders = errors.New("no headers have defined columns")
type SortOrder int
const (
SORT_ASC SortOrder = iota + 1
SORT_DESC
)
func (so SortOrder) String() string {
switch so {
case SORT_ASC:
return "ascending"
case SORT_DESC:
return "descending"
default:
panic("unhandled sort order for String")
}
}
// SortByNamedColumn performs an in-place row-sort.
func (t *ATable) SortByNamedColumn(name string, order SortOrder) error {
if t.columnNames == nil {
return ErrNoColumnHeaders
}
columnNumber, ok := t.columnNames[name]
if !ok {
return ErrorNoSuchColumn(name)
}
return t.SortByColumnNumber(columnNumber, order)
}
type tableSorter struct {
tb *ATable
column int
order SortOrder
}
func (t tableSorter) Len() int { return t.tb.NRows() }
func (t tableSorter) Swap(i, j int) {
t.tb.rows[i], t.tb.rows[j] = t.tb.rows[j], t.tb.rows[i]
}
func (t tableSorter) Less(i, j int) bool {
if t.order == SORT_ASC {
return t.tb.rows[i].cells[t.column].LessThan(&t.tb.rows[j].cells[t.column])
} else if t.order == SORT_DESC {
return t.tb.rows[j].cells[t.column].LessThan(&t.tb.rows[i].cells[t.column])
} else {
panic("unhandled order in tableSorter.Less")
}
}
func (t *ATable) SortByColumnNumber(sortCol int, order SortOrder) error {
if sortCol < 0 || sortCol >= t.nColumns {
return ErrorColumnOutOfRange(sortCol)
}
ts := tableSorter{t, sortCol, order}
sort.Sort(ts)
return nil
}