Search Apps Documentation Source Content File Folder Download Copy Actions Download

tablesort.gno

1.14 Kb ยท 39 lines
 1// Package tablesort provides functionality to render a Markdown table with sortable columns.
 2// It allows users to click on column headers to sort the table in ascending or descending sort direction.
 3// The sorting state is managed via URL query parameters.
 4// It displays an error if the table is malformed (e.g. rows with missing cells).
 5// Multiple tablesort can be rendered on the same page by using a paramPrefix for each Render (See the Render function).
 6package tablesort
 7
 8import (
 9	"sort"
10)
11
12// rowSorter implements sort.Interface for sorting rows by a specific column.
13type rowSorter struct {
14	rows      [][]string
15	colIndex  int
16	ascending bool
17}
18
19func (rs rowSorter) Len() int {
20	return len(rs.rows)
21}
22
23func (rs rowSorter) Less(i, j int) bool {
24	iCell := rs.rows[i][rs.colIndex]
25	jCell := rs.rows[j][rs.colIndex]
26	if rs.ascending {
27		return iCell < jCell
28	}
29	return iCell > jCell
30}
31
32func (rs rowSorter) Swap(i, j int) {
33	rs.rows[i], rs.rows[j] = rs.rows[j], rs.rows[i]
34}
35
36// SortRows sorts the rows slice by a given column index and direction
37func SortRows(rows [][]string, colIndex int, ascending bool) {
38	sort.Sort(rowSorter{rows, colIndex, ascending})
39}