Capy-Bearer Documentation

Sort a list or map

lib call

Capy

function sort(items : any, opt : any = {}) any
function sort(items : any, compare : function(left : any, right : any) s64) any

Description

Without a comparator, sort() sorts list strings in ascending lexical order. A non-string list element or a non-container input causes a runtime error. For a map, it sorts keys in ascending lexical order, regardless of value types. Numeric-looking map keys remain strings, so "10" comes before "2".

With a comparator, sort() compares values, not keys. Lists and maps can contain numbers, records, or other values. Equal values keep their original order. Each map entry keeps its key. The sort uses O(n log n) comparisons and O(n) working storage.

natural: true compares digit runs by their numeric value, as PHP strnatcmp does, so "img2" comes before "img10". A digit run with a leading zero compares digit by digit, and runs of whitespace are skipped. ignore_case: true compares ASCII letters without case. Together they match PHP strnatcasecmp and natcasesort. Both options apply to list strings and to map keys. Equal strings keep their original order.

Neither form changes the source container. Both map forms and the list comparator form share child objects with the source. The default list form returns sorted strings.

Maps otherwise retain insertion order. Use sort(map) explicitly when key order matters to a caller.

Parameters

items : the list or map to sort

opt : natural and ignore_case, both false by default

compare : optional comparator. Return -1 when left comes first, 0 when equal, or 1 when right comes first.

Return Values

A new container with the same map or list kind. The comparator form returns none for a non-container input.

Example

Capy

var items := split("two,one", ",")
print(join(sort(items), ","), "\n")

Output

one,two

Example

Capy

var items := any([10, 2, 1])
var ordered := sort(items, function(left : any, right : any) s64 {
    if s64(left) < s64(right) { return -1 }
    if s64(left) > s64(right) { return 1 }
    -> 0
})
print(join(ordered, ","), "\n")

Output

1,2,10

Example

Capy

var scores := {
	z: 2,
	a: 3,
	m: 1
}
print(join(keys(scores), ","), "\n")
print(join(keys(sort(scores)), ","), "\n")
var ranked := sort(scores, function(left : any, right : any) s64
{
	-> s64(left) - s64(right)
})
print(join(keys(ranked), ","), "\n")

Output

z,a,m
a,m,z
m,z,a