3

The title pretty much says it all. Does JavaScript guarantee a total order on objects when using the <, >, <= and >= operators?

I wrote some code just to check total ordering on some objects. The result is consistent with total ordering, but that doesn't prove anything:

function thereIsTotalOrder(items){
 var one, other, theThird;
 // warning: n^3 complexity follows
 // If a <= b and b <= a then a = b (antisymmetry);
 for(var i=0; i<items.length; i++){
 for(var j=0; j<items.length; j++){
 one = items[i];
 other = items[j];
 if((one <= other) && (other <= one) && (one != other)){
 return false;
 }
 }
 }
 // If a <= b and b <= c then a <= c (transitivity)
 for(var i=0; i<items.length; i++){
 for(var j=0; j<items.length; j++){
 for(var k=0; k<items.length; k++){
 one = items[i];
 other = items[j];
 theThird = items[k];
 if((one <= other) && (other <= theThird) && !(one <= theThird)) {
 return false;
 }
 }
 }
 }
 // a <= b or b <= a (totality). 
 for(var i=0; i<items.length; i++){
 for(var j=0; j<items.length; j++){
 one = items[i];
 other = items[j];
 if(!((one <= other) || (other <= one))) {
 return false;
 }
 }
 }
 return true;
}
function a(){};
function b(){};
var c = "foo";
var d = "bar";
var e = "bar";
var f = function(){};
var g = {name : "bananas"};
console.log(thereIsTotalOrder([a, b, c, d, e, f, g])); // prints "true"
asked Feb 8, 2015 at 3:58
1
  • JavaScript never guarantee any order on objects... Commented Feb 8, 2015 at 4:02

1 Answer 1

3

Depends on what objects we're considering. If we confine our attention to the class of numbers, then yes, the order will be total. As your example demonstrates, the same can be said of (at least some) strings. But totality doesn't seem to hold generally.

For instance, if you add var h = 5; to your declarations and then add h to your thereIsTotalOrder call, you will get a false. That's because in a state where h = 5 and c = 'foo', (hcch) is false (which means that totality is not satisfied).

As you rightly noted, while the absence of a false value returned by thereIsTotalOrder doesn't prove that all objects are totally ordered, the presence of a false value does prove that the order (if defined) between all objects is not total.

answered Feb 8, 2015 at 4:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.