Created
June 19, 2012 06:31
-
-
Save stereobooster/2952629 to your computer and use it in GitHub Desktop.
Underscore string descending sortBy
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
/** | |
* Underscore string descending sortBy | |
* usage: | |
* Sort by name ascending `_.sortBy(data, string_comparator('name'));` | |
* Sort by name descending `_.sortBy(data, string_comparator('-name'));` | |
*/ | |
var string_comparator = function(param_name, compare_depth) { | |
if (param_name[0] == '-') { | |
param_name = param_name.slice(1), | |
compare_depth = compare_depth || 10; | |
return function (item) { | |
return String.fromCharCode.apply(String, | |
_.map(item[param_name].slice(0, compare_depth).split(""), function (c) { | |
return 0xffff - c.charCodeAt(); | |
}) | |
); | |
}; | |
} else { | |
return function (item) { | |
return item[param_name]; | |
}; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment