Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Compare ¶
Example ¶
package main
import (
"fmt"
"math"
"github.com/dashjay/xiter/pkg/cmp"
)
func main() {
fmt.Println(cmp.Compare(1, 2))
fmt.Println(cmp.Compare("a", "aa"))
fmt.Println(cmp.Compare(1.5, 1.5))
fmt.Println(cmp.Compare(math.NaN(), 1.0))
}
Output: -1 -1 0 -1
func Less ¶
Example ¶
package main
import (
"fmt"
"math"
"github.com/dashjay/xiter/pkg/cmp"
)
func main() {
fmt.Println(cmp.Less(1, 2))
fmt.Println(cmp.Less("a", "aa"))
fmt.Println(cmp.Less(1.0, math.NaN()))
fmt.Println(cmp.Less(math.NaN(), 1.0))
}
Output: true true false true
func Or ¶
func Or[T comparable](vals ...T) T
Example ¶
package main
import (
"fmt"
"github.com/dashjay/xiter/pkg/cmp"
)
func main() {
// Suppose we have some user input
// that may or may not be an empty string
userInput1 := ""
userInput2 := "some text"
fmt.Println(cmp.Or(userInput1, "default"))
fmt.Println(cmp.Or(userInput2, "default"))
fmt.Println(cmp.Or(userInput1, userInput2, "default"))
}
Output: default some text some text
Example (Sort) ¶
package main
import (
"fmt"
"sort"
"strings"
"github.com/dashjay/xiter/pkg/cmp"
)
type Order struct {
Product string
Customer string
Price float64
}
type Orders []Order
func (o Orders) Len() int {
return len(o)
}
func (o Orders) Less(i, j int) bool {
a, b := o[i], o[j]
if cmp.Or(
strings.Compare(a.Customer, b.Customer),
strings.Compare(a.Product, b.Product),
cmp.Compare(b.Price, a.Price)) < 0 {
return true
} else {
return false
}
}
func (o Orders) Swap(i, j int) {
o[i], o[j] = o[j], o[i]
}
func main() {
orders := []Order{
{"foo", "alice", 1.00},
{"bar", "bob", 3.00},
{"baz", "carol", 4.00},
{"foo", "alice", 2.00},
{"bar", "carol", 1.00},
{"foo", "bob", 4.00},
}
//Sort by customer first, product second, and last by higher price
sort.Sort(Orders(orders))
// wait for the implement of slices.SortFunc
//SortFunc(orders, func(a, b Order) int {
// return cmp.Or(
// strings.Compare(a.Customer, b.Customer),
// strings.Compare(a.Product, b.Product),
// cmp.Compare(b.Price, a.Price),
// )
//})
for _, order := range orders {
fmt.Printf("%s %s %.2f\n", order.Product, order.Customer, order.Price)
}
}
Output: foo alice 2.00 foo alice 1.00 bar bob 3.00 foo bob 4.00 bar carol 1.00 baz carol 4.00
Types ¶
Click to show internal directories.
Click to hide internal directories.