Skip to content

Commit df9634c

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

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

naturalSort.js

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,30 +16,32 @@
1616
: define
1717
)
1818
/*define*/([], function factory() {
19-
20-
function naturalSort (a, b) {
2119
var re = /(^([+\-]?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?(?=\D|\s|$))|^0x[\da-fA-F]+$|\d+)/g,
2220
sre = /^\s+|\s+$/g, // trim pre-post whitespace
2321
snre = /\s+/g, // normalize all whitespace to single ' ' character
2422
dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
2523
hre = /^0x[0-9a-f]+$/i,
2624
ore = /^0/,
25+
b0re = /^\0/,
26+
e0re = /\0$/,
2727
i = function(s) {
2828
return (naturalSort.insensitive && ('' + s).toLowerCase() || '' + s).replace(sre, '');
2929
},
30+
normChunk = function(s, l) {
31+
// normalize spaces; find floats not starting with '0', string or 0 if not defined (Clint Priest)
32+
return (!s.match(ore) || l == 1) && parseFloat(s) || s.replace(snre, ' ').replace(sre, '') || 0;
33+
};
34+
35+
function naturalSort (a, b) {
3036
// convert all to strings strip whitespace
31-
x = i(a),
32-
y = i(b),
37+
var x = i(a) || '',
38+
y = i(b) || '',
3339
// 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'),
40+
xN = x.replace(re, '\0$1\0').replace(e0re,'').replace(b0re,'').split('\0'),
41+
yN = y.replace(re, '\0$1\0').replace(e0re,'').replace(b0re,'').split('\0'),
3642
// numeric, hex or date detection
3743
xD = parseInt(x.match(hre), 16) || (xN.length !== 1 && Date.parse(x)),
3844
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-
},
4345
oFxNcL, oFyNcL;
4446
// first try and sort Hex codes or Dates
4547
if (yD) {

0 commit comments

Comments
 (0)