natural

package module
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 3, 2023 License: Apache-2.0 Imports: 1 Imported by: 76

README

natural

Yet another natural sort, with 100% test coverage and a benchmark. It does not allocate memory, doesn't depend on package sort and hence doesn't depend on reflect. It is optimized for speed.

Go Reference codecov

Benchmarks

On Go 1.18.3.

$ go test -bench=. -cpu 1
goos: linux
goarch: amd64
pkg: github.com/maruel/natural
cpu: Intel(R) Core(TM) i7-10700 CPU @ 2.90GHz
BenchmarkLessDigitsTwoGroupsNative 331287298     3.597 ns/op   0 B/op   0 allocs/op
BenchmarkLessDigitsTwoGroups        32479050    36.55 ns/op    0 B/op   0 allocs/op
BenchmarkLessStringOnly            157775884     7.603 ns/op   0 B/op   0 allocs/op
BenchmarkLessDigitsOnly             69210796    17.52 ns/op    0 B/op   0 allocs/op
BenchmarkLess10Blocks                6331066   190.8 ns/op     0 B/op   0 allocs/op

On a Raspberry Pi 3:

$ go test -bench=. -cpu 1
goos: linux
goarch: arm
pkg: github.com/maruel/natural
BenchmarkLessDigitsTwoGroupsNative  14181789    86.57 ns/op    0 B/op   0 allocs/op
BenchmarkLessDigitsTwoGroups         1600195   748.9 ns/op     0 B/op   0 allocs/op
BenchmarkLessStringOnly              8286034   142.3 ns/op     0 B/op   0 allocs/op
BenchmarkLessDigitsOnly              3653055   331.4 ns/op     0 B/op   0 allocs/op
BenchmarkLess10Blocks                 310687  3838 ns/op       0 B/op   0 allocs/op

Coverage:

$ go test -cover
PASS
coverage: 100.0% of statements
ok     github.com/maruel/natural       0.012s

Documentation

Overview

Package natural defines a natural "less" to compare two strings while interpreting natural numbers.

This is occasionally nicknamed 'natsort'.

It does so with no memory allocation.

Example
package main

import (
	"fmt"
	"sort"
	"strings"

	"github.com/maruel/natural"
)

func main() {
	items := []string{
		"gpio10",
		"gpio1",
		"gpio20",
	}
	sort.Sort(natural.StringSlice(items))
	fmt.Println(strings.Join(items, "\n"))
}
Output:

gpio1
gpio10
gpio20

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Less

func Less(a, b string) bool

Less does a 'natural' comparison on the two strings.

It treats digits as decimal numbers, so that Less("10", "2") return false.

This function does no memory allocation.

Types

type StringSlice

type StringSlice []string

StringSlice attaches the methods of Interface to []string, sorting in increasing order using natural order.

func (StringSlice) Len

func (p StringSlice) Len() int

func (StringSlice) Less

func (p StringSlice) Less(i, j int) bool

func (StringSlice) Swap

func (p StringSlice) Swap(i, j int)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL