Scott Sauyet
4/30/2015 5:53:00 PM
jonas.thornvall@gmail.com wrote:
> Can one compare numeric strings of any size and decide which one
> bigger?
>
> I have a routine to compare anysize numbers read into array, but
> it would be smooth just to be able to compare a numeric string or
> integer of anysize, without function call.
With what tools? You could inline the code from (any non-recursive)
function call, I suppose, wherever you needed to do this, but that
would be ridiculous in the extreme. The language supports numbers
in a fairly simple format. The source-code format in which they're
supplied is well-documented. If you want to do more, and to treat
strings as numbers, you're really going to need your own functions.
There have been several such functions on this thread. They all
seem to have the same issue, which might or might not matter at all
to you. They assume that the data is not only well-structured, but
also normalized. I didn't look carefully, but if I'm not mistaken,
they would all report that "3456" is less than "001234".
Here is a function with a slightly different API that fixes that
issue:
var compare = function(a, b) {
if (!a || !a.length) {
return (b && b.length) ? 1 : 0;
}
if (!b || !b.length) {
return -1;
}
if (!Number(a[0])) {
return compare(a.slice(1), b);
}
if (Number(!b[0])) {
return compare(a, b.slice(1));
}
return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 :
compare(a.slice(1), b.slice(1));
};
But this one is limited to the recursion depth of the underlying ES
engine. One could alter it to make an iterative version if desired.
Note that its API is different. It returns -1 if the first value is
smaller than the second, +1 if it's larger, and 0 if the two values
are equal, much the same as you would do with a comparator passed to
`Array.prototype.sort`. It would be easy enough to wrap this with a
function to generate the API you supplied, if you chose to do so. But
there is a lot to be said for the comparator API.
-- Scott