Skip to content

Instantly share code, notes, and snippets.

@cmstead
Last active September 19, 2015 20:52
Show Gist options
  • Save cmstead/9ea2da73f0675707a7e3 to your computer and use it in GitHub Desktop.
Save cmstead/9ea2da73f0675707a7e3 to your computer and use it in GitHub Desktop.
Sort factory supporting array of columns and SQL-like ascending/descending sorting
// Full sorting factory with SQL-like ascending and descending sort functionality
var keyedSortFactory = (function(){
'use strict';
function keyedSort(sortArray, a, b){
var result = 0,
index = 0,
sortArrayLength = sortArray.length;
while(result === 0 && index < sortArrayLength){
result = sortArray[index](a, b);
}
return result
}
function keySort(key, a, b){
var aValue = a[key],
bValue = b[key],
result = aValue < bValue ? -1 : 1;
return aValue === bValue ? 0 : result;
}
function reverseSort(sortFunction){
return function(a, b){
return -1 * sortFunction(a, b);
}
}
function sortFactory(sortString){
var sortTokens = sortString.split(' '),
key = sortTokens[0],
direction = Boolean(sortTokens[1]) ? sortTokens[1].toLowerCase() : 'asc',
sortFunction = keyedSort.bind(null, key);
return direction === 'desc' ? reverseSort(sortFunction) : sortFunction;
}
function keyedSortFactory(sortStrings){
var sortFunctions = sortStrings.map(sortFactory);
return keyedSort.bind(null, sortFunctions);
}
return {
build: keyedSortFactory
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment