11.8.5 Abstract Relational Comparison Algorithm

2010-05-17

Relational comparison function (not actually defined as a function in the specification, but all the same for all intentions and purposes). It takes three arguments; x:mixed, y:mixed, leftFirst:boolean and returns a boolean, indicating whether the x
Code: (Meta Ecma)
function RelationalComparison(x, y, leftFirst) {
if (leftFirst !== false) leftFirst = true; // *sigh*
if (leftFirst) {
var px = ToPrimitive(x, "Number");
var py = ToPrimitive(y, "Number");
} else {
var py = ToPrimitive(y, "Number");
var px = ToPrimitive(x, "Number");
}
if (Type(px) != 'string' || Type(py) != 'string') {
// px/py are primitives so calling order is unimportant, unlike above
var nx = ToNumber(px);
var ny = ToNumber(py);
if (isNaN(nx)) return undefined;
if (isNaN(ny)) return undefined;
if (nx == ny) return false;
if (nx === +0 && ny === -0) return false;
if (nx === -0 && ny === +0) return false;
if (nx === infinity) return false;
if (ny === infinity) return true;
if (ny === -infinity) return false;
if (nx === -infinity) return true;
return nx < ny; // if "mathematical value" x } else { // px and py are strings
if (px.indexOf(py) === 0) return false;
if (py.indexOf(py) === 0) return true;
// this is just a naieve algo
// a more efficient algo exists but i cant remember it
// from the top of my head :)
var k;
for (k=0; k if (px[k] != py[k]) break;
}
// k must now be the first offending position
m = px[k];
n = px[k];
return m < n;
}
}

Note that this function always applies the lesser than operator's behaviour. The other operators invert the processing order of the parameters or or extend the result.

In this function, strings comparison is purely based on (Unicode) code unit values. Ecmascript does not put any effort into a more semantic ordering. This means that "10"<"2", "alpha"<"beta", "pappa"<"pappi" and "Beta"<"alpha". Especially when comparing stringed numbers the results might be a little off (since 10 is less than 2). Uppercase will always preceed any lowercase (so not only "a"<"b" and "A"<"a" but also "Z"<"a". In that ordering, numbers come before uppercase. For the common ASCII chars, this ASCII table indicates the ordering.

Because code points are the only values considered, strings that would be canonically (after evaluation) equal according to the Unicode specification, are probably not according to this function.