Skip to content

Instantly share code, notes, and snippets.

@tilast
Last active August 29, 2015 14:08
Show Gist options
  • Save tilast/02a68853e6983bfc884e to your computer and use it in GitHub Desktop.
Save tilast/02a68853e6983bfc884e to your computer and use it in GitHub Desktop.
var sortingEngine = (function() {
function dynamicSort(property) {
var sortOrder = 1;
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a,b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
function dynamicSortMultiple(multiplySort) {
/*
* save the arguments object as it will be overwritten
* note that arguments object is an array-like object
* consisting of the names of the properties to sort by
*/
var props = multiplySort;
return function (obj1, obj2) {
var i = 0, result = 0, numberOfProperties = props.length;
/* try getting a different result from 0 (equal)
* as long as we have extra properties to compare
*/
while(result === 0 && i < numberOfProperties) {
result = dynamicSort(props[i])(obj1, obj2);
i++;
}
return result;
}
}
return {
dynamicSort: dynamicSort,
dynamicSortMultiple: dynamicSortMultiple
}
})();
sortingEngine.dynamicSort(smth);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment