Skip to content

Commit f8d8395

Browse files
committed
Declare regexps and functions outside of naturalSort() - speed increased by ~12%
1 parent 4bd01a5 commit f8d8395

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

naturalSort.js

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,29 +17,32 @@
1717
)
1818
/*define*/([], function factory() {
1919

20-
function naturalSort (a, b) {
2120
var re = /(^([+\-]?(?:\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[\da-fA-F]+$|\d+)/g,
2221
sre = /^\s+|\s+$/g, // trim pre-post whitespace
2322
snre = /\s+/g, // normalize all whitespace to single ' ' character
2423
dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
2524
hre = /^0x[0-9a-f]+$/i,
2625
ore = /^0/,
26+
b0re = /^\0/,
27+
e0re = /\0$/,
2728
i = function(s) {
2829
return (naturalSort.insensitive && ('' + s).toLowerCase() || '' + s).replace(sre, '');
2930
},
31+
normChunk = function(s, l) {
32+
// normalize spaces; find floats not starting with '0', string or 0 if not defined (Clint Priest)
33+
return (!s.match(ore) || l == 1) && parseFloat(s) || s.replace(snre, ' ').replace(sre, '') || 0;
34+
};
35+
36+
function naturalSort (a, b) {
3037
// convert all to strings strip whitespace
31-
x = i(a) || '',
38+
var x = i(a) || '',
3239
y = i(b) || '',
3340
// chunk/tokenize
34-
xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
35-
yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
41+
xN = x.replace(re, '\0$1\0').replace(e0re,'').replace(b0re,'').split('\0'),
42+
yN = y.replace(re, '\0$1\0').replace(e0re,'').replace(b0re,'').split('\0'),
3643
// numeric, hex or date detection
3744
xD = parseInt(x.match(hre), 16) || (xN.length !== 1 && Date.parse(x)),
3845
yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null,
39-
normChunk = function(s, l) {
40-
// normalize spaces; find floats not starting with '0', string or 0 if not defined (Clint Priest)
41-
return (!s.match(ore) || l == 1) && parseFloat(s) || s.replace(snre, ' ').replace(sre, '') || 0;
42-
},
4346
oFxNcL, oFyNcL;
4447
// first try and sort Hex codes or Dates
4548
if (yD) {

0 commit comments

Comments
 (0)