Skip to content

Commit

Permalink
Declare regexps and functions outside of naturalSort() - speed increa…
Browse files Browse the repository at this point in the history
…sed by ~12%
  • Loading branch information
duzun committed Oct 22, 2015
1 parent 4bd01a5 commit f8d8395
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions naturalSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,29 +17,32 @@
)
/*define*/([], function factory() {

function naturalSort (a, b) {
var re = /(^([+\-]?(?:\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[\da-fA-F]+$|\d+)/g,
sre = /^\s+|\s+$/g, // trim pre-post whitespace
snre = /\s+/g, // normalize all whitespace to single ' ' character
dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
hre = /^0x[0-9a-f]+$/i,
ore = /^0/,
b0re = /^\0/,
e0re = /\0$/,
i = function(s) {
return (naturalSort.insensitive && ('' + s).toLowerCase() || '' + s).replace(sre, '');
},
normChunk = function(s, l) {
// normalize spaces; find floats not starting with '0', string or 0 if not defined (Clint Priest)
return (!s.match(ore) || l == 1) && parseFloat(s) || s.replace(snre, ' ').replace(sre, '') || 0;
};

function naturalSort (a, b) {
// convert all to strings strip whitespace
x = i(a) || '',
var x = i(a) || '',
y = i(b) || '',
// chunk/tokenize
xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
xN = x.replace(re, '\0$1\0').replace(e0re,'').replace(b0re,'').split('\0'),
yN = y.replace(re, '\0$1\0').replace(e0re,'').replace(b0re,'').split('\0'),
// numeric, hex or date detection
xD = parseInt(x.match(hre), 16) || (xN.length !== 1 && Date.parse(x)),
yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null,
normChunk = function(s, l) {
// normalize spaces; find floats not starting with '0', string or 0 if not defined (Clint Priest)
return (!s.match(ore) || l == 1) && parseFloat(s) || s.replace(snre, ' ').replace(sre, '') || 0;
},
oFxNcL, oFyNcL;
// first try and sort Hex codes or Dates
if (yD) {
Expand Down

0 comments on commit f8d8395

Please sign in to comment.