naturalSort.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
  3. * Author: Jim Palmer (based on chunking idea from Dave Koelle)
  4. */
  5. /*jshint unused:false */
  6. module.exports = function naturalSort (a, b) {
  7. "use strict";
  8. var re = /(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,
  9. sre = /(^[ ]*|[ ]*$)/g,
  10. dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
  11. hre = /^0x[0-9a-f]+$/i,
  12. ore = /^0/,
  13. i = function(s) { return naturalSort.insensitive && ('' + s).toLowerCase() || '' + s; },
  14. // convert all to strings strip whitespace
  15. x = i(a).replace(sre, '') || '',
  16. y = i(b).replace(sre, '') || '',
  17. // chunk/tokenize
  18. xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
  19. yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
  20. // numeric, hex or date detection
  21. xD = parseInt(x.match(hre), 16) || (xN.length !== 1 && x.match(dre) && Date.parse(x)),
  22. yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null,
  23. oFxNcL, oFyNcL;
  24. // first try and sort Hex codes or Dates
  25. if (yD) {
  26. if ( xD < yD ) { return -1; }
  27. else if ( xD > yD ) { return 1; }
  28. }
  29. // natural sorting through split numeric strings and default strings
  30. for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
  31. // find floats not starting with '0', string or 0 if not defined (Clint Priest)
  32. oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
  33. oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
  34. // handle numeric vs string comparison - number < string - (Kyle Adams)
  35. if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; }
  36. // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
  37. else if (typeof oFxNcL !== typeof oFyNcL) {
  38. oFxNcL += '';
  39. oFyNcL += '';
  40. }
  41. if (oFxNcL < oFyNcL) { return -1; }
  42. if (oFxNcL > oFyNcL) { return 1; }
  43. }
  44. return 0;
  45. };