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
-- 
Juju-dev mailing list
[email protected]
Modify settings or unsubscribe at: 
https://lists.ubuntu.com/mailman/listinfo/juju-dev

Reply via email to