extend("test")
extend("array")
describe("array:sort default ordering", () => {
it("sorts integers ascending", () => {
expect_equal(array:sort([4,1,3,2]), [1,2,3,4])
})
it("sorts floats ascending", () => {
expect_equal(array:sort([3.5, 1.25, 2.0, 2.0]), [1.25, 2.0, 2.0, 3.5])
})
it("sorts strings lexicographically", () => {
expect_equal(array:sort(["b","c","a"]), ["a","b","c"])
})
it("sorts a homogeneous mixed int array", () => {
expect_equal(array:sort([3,2,5,1]), [1,2,3,5])
})
})
describe("array:sort with comparator", () => {
it("sorts integers descending", () => {
expect_equal(array:sort((a,b) => b - a, [4,1,3,2]), [4,3,2,1])
})
it("supports partial usage with known comparator", () => {
desc = array:sort((a,b) => b - a)
expect_equal(desc([1,5,3]), [5,3,1])
})
it("supports placeholder usage with known array", () => {
arr = [9,7,8]
need_cmp = array:sort(_, arr)
expect_equal(need_cmp((a,b) => a - b), [7,8,9])
})
it("supports fully partial usage", () => {
p0 = array:sort()
p1 = p0((a,b) => a - b)
expect_equal(p1([3,1,2]), [1,2,3])
})
it("errors if comparator is not a function", () => {
test:expect_error(() => array:sort(123, [1,2,3]))
})
})
describe("array:sort_by key extraction", () => {
it("sorts numbers by their negated value", () => {
expect_equal(array:sort_by(x => -x, [3,1,2]), [3,2,1])
})
it("sorts keyed objects by numeric key", () => {
people = [
[name:"Abby", age:7, hair:"blond"],
[name:"Fred", age:12, hair:"brown"],
[name:"Rusty", age:30, hair:"brown"],
[name:"Alois", age:65, disposition:"surly"]
]
by_age = x => array:prop("age", x)
sorted = array:sort_by(by_age, people)
expect_equal(sorted, [
[name:"Abby", age:7, hair:"blond"],
[name:"Fred", age:12, hair:"brown"],
[name:"Rusty", age:30, hair:"brown"],
[name:"Alois", age:65, disposition:"surly"]
])
})
it("supports partial usage", () => {
by_abs = array:sort_by(x => (x < 0 ? -x : x))
expect_equal(by_abs([3,-1,2,-5]), [-1,2,3,-5])
})
it("supports placeholder usage with known array", () => {
arr = ["b","aa","c"]
need_key = array:sort_by(_, arr)
expect_equal(need_key(x => x), ["aa","b","c"])
})
it("errors if key extractor is not a function", () => {
test:expect_error(() => array:sort_by(42, [1,2,3]))
})
})
describe("array:sort_with multi-comparator", () => {
it("sorts with a single comparator", () => {
expect_equal(array:sort_with((a,b) => a - b, [3,1,2]), [1,2,3])
})
it("supports partial usage with comparator list first", () => {
cmp_desc = (a,b) => b - a
sorter = array:sort_with([cmp_desc])
expect_equal(sorter([1,4,2,3]), [4,3,2,1])
})
it("supports placeholder usage with known array", () => {
arr = [5,1,4]
need_comps = array:sort_with(_, arr)
expect_equal(need_comps((a,b) => a - b), [1,4,5])
})
it("errors when comparators are not function(s)", () => {
test:expect_error(() => array:sort_with(123, [1,2,3]))
test:expect_error(() => array:sort_with(["not a fn"], [1,2,3]))
})
})