natsort

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2023 License: MIT Imports: 1 Imported by: 0

README

natsort

build-img pkg-img reportcard-img coverage-img version-img

Natural sorting in Go, see Wikipedia.

Features

  • Fast.
  • Simple API.
  • Dependency-free.

See these docs for more details.

Install

Go version 1.18+

go get github.com/cristalhq/natsort

Example

files := []string{"img12.png", "img10.png", "img2.png", "img1.png"}

fmt.Println("Lexicographically:")

sort.Strings(files)
for _, f := range files {
	fmt.Println(f)
}

fmt.Println("\nNaturally:")

natsort.Sort(files)
for _, f := range files {
	fmt.Println(f)
}

// Output:
// Lexicographically:
// img1.png
// img10.png
// img12.png
// img2.png
//
// Naturally:
// img1.png
// img2.png
// img10.png
// img12.png

See examples: example_test.go.

License

MIT License.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsSorted

func IsSorted[T ~string](s []T) bool

IsSorted reports whether slice is sorted in natural order.

Example
package main

import (
	"fmt"

	"github.com/cristalhq/natsort"
)

func main() {
	files := []string{"img12.png", "img10.png", "img2.png", "img1.png"}

	if natsort.IsSorted(files) {
		fmt.Println("impossible!")
	}

	natsort.Sort(files)

	if !natsort.IsSorted(files) {
		fmt.Println("impossible!")
	}

}
Output:

func Less

func Less[T ~string](a, b T) bool

Less reports whether a is less than b ordered naturally.

func Sort

func Sort[T ~string](x []T)

Sort slice with natural order.

Example
package main

import (
	"fmt"
	"sort"

	"github.com/cristalhq/natsort"
)

func main() {
	files := []string{"img12.png", "img10.png", "img2.png", "img1.png"}

	fmt.Println("Lexicographically:")

	sort.Strings(files)
	for _, f := range files {
		fmt.Println(f)
	}

	fmt.Println("\nNaturally:")

	natsort.Sort(files)
	for _, f := range files {
		fmt.Println(f)
	}

}
Output:

Lexicographically:
img1.png
img10.png
img12.png
img2.png

Naturally:
img1.png
img2.png
img10.png
img12.png

Types

type Slice

type Slice[T ~string] []T

Slice implements sort.Interface allowing to sort in natural order.

func (Slice[T]) Len

func (p Slice[T]) Len() int

func (Slice[T]) Less

func (p Slice[T]) Less(i, j int) bool

func (Slice[T]) Swap

func (p Slice[T]) Swap(i, j int)

Jump to

Keyboard shortcuts

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