JRS: In article <11**********************@b28g2000cwb.googlegroups .com>
, dated Fri, 28 Jul 2006 02:07:30 remote, seen in
news:comp.lang.javascript, RobG <rg***@iinet.net.auposted :
>
ba*****************@gmail.com wrote:
> Can u give me a suggestion.
That must seem very polite, to a Burmese.
>An algorithm is:
- get the values as strings (input elements will return strings)
- check they are both integers
But -79, +3, 123e45, 123e4567 are all integers. *Probably* he means
all-digit strings.
- remove leading zeros
Probably. But 077 = 0x3F = 63 = 0.63e2, maybe.
>function isBigger(a, b)
{
// Make sure they are integers
var re = new RegExp('\\D','g');
I don't see that 'g' is needed, any non-digit fails an all-digit format.
if (re.test(a) || re.test(b)){
return undefined;
}
// Trim leading zeros
a = a.replace(/^0+/g,'');
b = b.replace(/^0+/g,'');
Ditto.
// Check lengths
if (a.length != b.length){
return (a.length b.length);
}
// Compare digits
var a = a.split('');
var b = b.split('');
for (var i=0, j=a.length; i<j; i++){
if (+a[i] b[i]) return true;
}
return false;
}
It could be better to compare a.charAt(i) with b.charAt(i); it saves
generating length+length objects. Perhaps I mean charCodeAt throughout.
I suspect you've not handled b<a, though he seems not to need that.
I think I'd go lower-level.
Take strings A & B.
From the Subject line, we can take it that the numbers consist only of
decimal digits, to be interpreted as decimal (if doubtful, use a
preliminary RegExp[*]).
We can also take it that they are of equal length; and, if not, it's
easy to prepend a string of zeroes to the shorter. At this stage they
can in fact be compared as strings.
Otherwise, loop through both strings, subtracting A.charAt[i] and
B.charAt[i]. At the first difference, return that difference. Finally
return 0 (the final difference; so it'd be nice to use
Dif = cA-cB ; if (!Dif) break ; ... return Dif ; ).
ISTM that charAt[i] should be swift given what ECMA seems to say about
all characters using 16 bits. If charAt[50] requires 100 or more bytes
to be considered, I'd not want to use it here.
ISTM that the strings could perhaps be broken up into ten-digit units
with a cunning RegExp (actually, cunning not needed where the length is
a multiple of 10) match, and the resulting strings compared numerically
in turn with unary +.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/>? JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.