Created
November 27, 2014 13:00
-
-
Save gkucmierz/b38b3794ab31df00462b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
// default comparing functions for specified types | |
// in config can be defined custom one | |
var dataTypes = { | |
'string': function(strA, strB) { | |
return strA.localeCompare(strB); | |
}, | |
'number': function(numA, numB) { | |
return numA - numB; | |
}, | |
'enum': function(valA, valB, config) { | |
return config.order.indexOf(valA) - config.order.indexOf(valB); | |
} | |
}; | |
var getDirNumber = (function() { | |
var map = { | |
'asc': 1, | |
'dsc': -1 | |
}; | |
return function(dir) { | |
// return direction of sorting | |
// dont sort (0) if its not fit to any direction | |
return dir && map[dir] || 0; | |
}; | |
})(); | |
var getCompareFn = function(rule, sortingConfig) { | |
var dataType = sortingConfig.properties[rule.property].dataType; | |
// custom function can be set in rule, or its taken from custom dataTypes, and default ones | |
var comparingFn = rule.custom || sortingConfig.dataTypes[dataType] || dataTypes[dataType]; | |
return function(itemA, itemB) { | |
return getDirNumber(rule.dir) * comparingFn( | |
itemA[rule.property], | |
itemB[rule.property], | |
rule.config | |
); | |
}; | |
}; | |
return function(data, sortingRules, sortingConfig) { | |
var l = sortingRules.length; | |
data.sort(function(itemA, itemB) { | |
var compareResult = 0; | |
for (var i = 0; i < l; ++i) { | |
compareResult = getCompareFn(sortingRules[i], sortingConfig)(itemA, itemB); | |
if (compareResult !== 0) { | |
break; | |
} | |
} | |
return compareResult; | |
}); | |
}; | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment