Skip to content

Instantly share code, notes, and snippets.

@andrewbranch
Last active September 1, 2015 01:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewbranch/03fe7cb48ca1730e075f to your computer and use it in GitHub Desktop.
Save andrewbranch/03fe7cb48ca1730e075f to your computer and use it in GitHub Desktop.
Variadic sort
function getTestPeople() {
return [{
name: "Kylie",
age: 18
}, {
name: "Andrew",
age: 23
}, {
name: "Andrew",
age: 18
}, {
name: "Clay",
age: 23
}];
}
function sort() {
var sortFunctions = Array.prototype.slice.call(arguments);
var lastArgument = sortFunctions.pop();
if (lastArgument.sort) {
return lastArgument.sort(function(a, b) {
for (var i = 0; i < sortFunctions.length; i++) {
var order = sortFunctions[i](a, b);
if (order !== 0) {
return order;
}
}
return 0;
});
}
return sortFunctions.reduce(function(bound, arg) {
return bound.bind(this, arg);
}.bind(this), sort).bind(this, lastArgument);
}
function byName(a, b) {
if (a.name > b.name) {
return 1;
} else if (a.name < b.name) {
return -1;
}
return 0;
}
function byAge(a, b) {
return a.age - b.age;
}
var sortByAgeThenName = sort(
byAge,
byName
);
var sortByNameThenAge = sort(
byName,
byAge
);
console.log('By Age Then Name');
console.log(JSON.stringify(sortByAgeThenName(getTestPeople()), null, 2));
console.log('By Name Then Age');
console.log(JSON.stringify(sortByNameThenAge(getTestPeople()), null, 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment