Natural sorting helper
Menno Smits
menno.smits at canonical.com
Wed Jun 22 08:35:08 UTC 2016
Hi everyone,
Earlier this week I needed to be able sort a slice containing unit names
and machine ids in a way that would make sense to a human. For example, a
conventional string sort would order a list of machine ids like this:
0
10
3
3/lxd/1
3/lxd/10
3/lxd/11
3/lxd/2
4
when what I really wanted was:
0
3
3/lxd/1
3/lxd/2
3/lxd/10
3/lxd/11
4
10
Tim pointed me at something that Anastasia had already done for formatting
the output from some Juju CLI commands. This was close so I extracted it to
github.com/juju/utils and generalised it. An in-place sort can be performed
like this:
utils.SortStringsNaturally(someSliceOfStrings)
The implementation is here:
https://github.com/juju/utils/blob/master/naturalsort.go
https://github.com/juju/utils/blob/master/naturalsort_test.go
Consider using it if your code needs to sort machine ids, unit names, tag
strings, IP addresses and any other slice of strings which contain sections
of digits.
- Menno
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.ubuntu.com/archives/juju-dev/attachments/20160622/d7d7d9a1/attachment.html>
More information about the Juju-dev
mailing list