[].sort()
can take a compare function
the compare function
can be given as the only parameter to sort()
(and gets used by it)
let compareFunctionUsed;
const compare = () => { compareFunctionUsed = true };
[2, 1].sort();
assert.equal(compareFunctionUsed, true);
is called with two values to be compared
let parameters = [];
const compare = (...args) => {parameters = ____;};
[2, 1].sort(compare);
assert.ok(parameters.includes(1));
assert.ok(parameters.includes(2));
is called multiple times (depending how the sort algorithm is implemented)
let callCount = 0;
const compare = () => {callCount--};
[3, 1, 2].sort();
assert.ok(callCount > 1);
the return value of the compare function indicates how the two values compare
examples
sort numbers
const numericCompare = (a, b) => 0;
assert.deepEqual([1, 11, 2].sort(numericCompare), [1, 2, 11]);
sort number-like values
const ensuredNumericCompare = () => {};
assert.deepEqual(['1', '23', 2, ' 3 '].sort(ensuredNumericCompare), ['1', 2, ' 3 ', '23']);
custom compare algorithm
const monthOrder = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
const monthCompare = (a, b) => a + b;
assert.deepEqual(['May', 'Apr', 'Feb'].sort(monthCompare), ['Feb', 'Apr', 'May']);
Links
mdn
docs
Very detailed description of how `sort()` works.
announcement
Announcement of this kata on twitter.