naturalSort.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. let _ = require('underscore');
  2. _.mixin({
  3. sortByNat: function (obj, value, context) {
  4. var iterator = _.isFunction(value) ? value : function (obj) {
  5. return obj[value];
  6. };
  7. return _.pluck(_.map(obj, function (value, index, list) {
  8. return {
  9. value: value,
  10. index: index,
  11. criteria: iterator.call(context, value, index, list)
  12. };
  13. }).sort(function (left, right) {
  14. var a = left.criteria;
  15. var b = right.criteria;
  16. return naturalSort(a, b);
  17. }), 'value');
  18. }
  19. });
  20. function naturalSort(a, b) {
  21. var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
  22. sre = /(^[ ]*|[ ]*$)/g,
  23. dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
  24. hre = /^0x[0-9a-f]+$/i,
  25. ore = /^0/,
  26. i = function (s) {
  27. return naturalSort.insensitive && ('' + s).toLowerCase() || '' + s
  28. },
  29. // convert all to strings strip whitespace
  30. x = i(a).replace(sre, '') || '',
  31. y = i(b).replace(sre, '') || '',
  32. // chunk/tokenize
  33. xN = x.replace(re, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0'),
  34. yN = y.replace(re, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0'),
  35. // numeric, hex or date detection
  36. xD = parseInt(x.match(hre)) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
  37. yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null,
  38. oFxNcL, oFyNcL;
  39. // first try and sort Hex codes or Dates
  40. if (yD)
  41. if (xD < yD) return -1;
  42. else if (xD > yD) return 1;
  43. // natural sorting through split numeric strings and default strings
  44. for (var cLoc = 0, numS = Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
  45. // find floats not starting with '0', string or 0 if not defined (Clint Priest)
  46. oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
  47. oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
  48. // handle numeric vs string comparison - number < string - (Kyle Adams)
  49. if (isNaN(oFxNcL) !== isNaN(oFyNcL)) {
  50. return (isNaN(oFxNcL)) ? 1 : -1;
  51. }
  52. // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
  53. else if (typeof oFxNcL !== typeof oFyNcL) {
  54. oFxNcL += '';
  55. oFyNcL += '';
  56. }
  57. if (oFxNcL < oFyNcL) return -1;
  58. if (oFxNcL > oFyNcL) return 1;
  59. }
  60. return 0;
  61. }
  62. // extend Array to have a natural sort
  63. Array.prototype.sortNat = function () {
  64. return Array.prototype.sort.call(this, naturalSort)
  65. };