2 natcompare.js -- Perform 'natural order' comparisons of strings in JavaScript.
3 Copyright (C) 2005 by SCK-CEN (Belgian Nucleair Research Centre)
4 Written by Kristof Coomans <kristof[dot]coomans[at]sckcen[dot]be>
6 Based on the Java version by Pierre-Luc Paour, of which this is more or less a straight conversion.
7 Copyright (C) 2003 by Pierre-Luc Paour <natorder@paour.com>
9 The Java version was based on the C version by Martin Pool.
10 Copyright (C) 2000 by Martin Pool <mbp@humbug.org.au>
12 This software is provided 'as-is', without any express or implied
13 warranty. In no event will the authors be held liable for any damages
14 arising from the use of this software.
16 Permission is granted to anyone to use this software for any purpose,
17 including commercial applications, and to alter it and redistribute it
18 freely, subject to the following restrictions:
20 1. The origin of this software must not be misrepresented; you must not
21 claim that you wrote the original software. If you use this software
22 in a product, an acknowledgment in the product documentation would be
23 appreciated but is not required.
24 2. Altered source versions must be plainly marked as such, and must not be
25 misrepresented as being the original software.
26 3. This notice may not be removed or altered from any source distribution.
30 function isWhitespaceChar(a
)
33 charCode
= a
.charCodeAt(0);
45 function isDigitChar(a
)
48 charCode
= a
.charCodeAt(0);
50 if ( charCode
>= 48 && charCode
<= 57 )
60 function compareRight(a
,b
)
69 // The longest run of digits wins. That aside, the greatest
70 // value wins, but we can't know that it will until we've scanned
71 // both numbers to know that they have the same magnitude, so we
72 // remember it in BIAS.
78 && !isDigitChar(cb
)) {
80 } else if (!isDigitChar(ca
)) {
82 } else if (!isDigitChar(cb
)) {
91 } else if (ca
== 0 && cb
== 0) {
97 function natcompare(a
,b
) {
100 var nza
= 0, nzb
= 0;
106 // only count the number of zeroes leading the last number compared
112 // skip over leading spaces or zeros
113 while ( isWhitespaceChar( ca
) || ca
=='0' ) {
117 // only count consecutive zeroes
124 while ( isWhitespaceChar( cb
) || cb
== '0') {
128 // only count consecutive zeroes
135 // process run of digits
136 if (isDigitChar(ca
) && isDigitChar(cb
)) {
137 if ((result
= compareRight(a
.substring(ia
), b
.substring(ib
))) != 0) {
142 if (ca
== 0 && cb
== 0) {
143 // The strings compare the same. Perhaps the caller
144 // will want to call strcmp to break the tie.
150 } else if (ca
> cb
) {