Skip to content

Sorting by several keys

collectionsAll subjects

Comparators are pure functions with three possible answers, which makes them unusually easy to test and unusually often untested. The tie-break only runs when the first key is equal — a case a suite of distinct fixtures never reaches.

The module under test

1
export function byKey(key, direction) {
2
const sign = direction === "desc" ? -1 : 1;
3
return (a, b) => {
4
const left = a[key];
5
const right = b[key];
6
if (left === right) {
7
return 0;
8
}
9
if (left === undefined) {
10
return 1;
11
}
12
if (right === undefined) {
13
return -1;
14
}
15
return left < right ? -sign : sign;
16
};
17
}
18
19
export function sortBy(items, comparators) {
20
return items.slice().sort((a, b) => {
21
for (const compare of comparators) {
22
const result = compare(a, b);
23
if (result !== 0) {
24
return result;
25
}
26
}
27
return 0;
28
});
29
}
30

Your tests

Mutants

Mutation score
Survived
0
Killed
0 / 0
Line coverage
Tests
0
Assertion width
Cycle
    survivedkilledtimed outequivalentnot run