Skip to content

Instantly share code, notes, and snippets.

@michaeljacobdavis
Created May 31, 2013 03:54
Show Gist options
  • Save michaeljacobdavis/5682856 to your computer and use it in GitHub Desktop.
Save michaeljacobdavis/5682856 to your computer and use it in GitHub Desktop.
function sortBy(sequence, sorters) {
return sequence.slice().sort(function (a, b) {
var comparison = 0;
for (var i = 0; i < sorters.length; ++i) {
comparison = sorters[i](a, b);
if (comparison !== 0) {
return comparison;
}
}
return comparison;
});
}
it('should sort by using the comparator given', function () {
// Given
var list = [7, 4, 5];
var comparator = function(a, b) {
return a - b;
};
// When
var sortedList = sortBy(list, [comparator]);
// Then
expect(sortedList[0]).toBe(4);
expect(sortedList[1]).toBe(5);
expect(sortedList[2]).toBe(7);
});
it('should not modify the original', function () {
// Given
var list = [7, 4, 5];
var comparator = function (a, b) {
return a - b;
};
// When
var sortedList = sortBy(list, [comparator]);
// Then
expect(list[0]).toBe(7);
expect(list[1]).toBe(4);
expect(list[2]).toBe(5);
});
it('should use subsequent comparators if the result of the current one is a tie', function () {
// Given
var list = [{ a: 1, b: 2 }, { a: 1, b: 1 }, { a: 1, b: 0 }];
// Asc
var comparator1 = function (a, b) {
return a.a - b.a;
};
// Desc
var comparator2 = function (a, b) {
return b.b - a.b;
};
// When
var sortedList = sortBy(list, [comparator1, comparator2]);
// Then
expect(list[0].b).toBe(2);
expect(list[1].b).toBe(1);
expect(list[2].b).toBe(0);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment