Roman
Roman

Reputation: 1168

JavaScript localeCompare() returns different result than Java compareTo()

What I am trying to achieve is to synchronize the outcome of these two functions. These methods return number indicating whether a reference string comes before or after or is the same as the given string in sort order.

The JavaScript localeCompare has many parameters to be set but nothing from what I have tried worked.

**Java returns**:      **JavaScript returns**:
Sensor             Sensor
SensorDus          Sensor DUS
SensorEnv          Sensor E
Sensor DUS         SensorDUS
Sensor E           Sensor Env

It looks like that the difference it those two methods is how they return the numbers. A negative number if the reference string occurs before the compare string; positive if the reference string occurs after the compare string; 0 if they are equivalent.

Any ideas if this is somehow possible?

Upvotes: 3

Views: 794

Answers (1)

Roman
Roman

Reputation: 1168

My solution to the problem. Instead of using localeCompare() I rewrote the Java compareTo() into JavaScript method. The java method returned positive (higher) number for white space as opposed to string without a white space in JavaScript.

localCompareAsInJava: function(t1,t2)
{
  var len1 = t1.length;
  var len2 = t2.length;
  var lim = Math.min(t1.length, t2.length);

  var v1 = t1;
  var v2 = t2;

  var k = 0;
  while(k < lim)
  {
    var c1 = v1[k];
    var c2 = v2[k];
    if(c1 != c2)
    {
      if(c1.charCodeAt(0) == 32 )
      {
        var charWithSpace = c1.charCodeAt(0) + c2.charCodeAt(0); 
        return charWithSpace;
      }
      else{
        return c1.charCodeAt(0) - c2.charCodeAt(0);
      }

    }
    k++;
  }
  return len1 - len2;
}

Upvotes: 3

Related Questions