Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the Javascript '>' operator compare characters with a space?

Tags:

javascript

I am trying to understand this expression:

((ch = stream.getChar()) > ' ')

Here, getChar() gets a character. How does this greater-than comparision operator check if any char is greater than an empty space?

Is this possible?

like image 425
Guilherme Longo Avatar asked Mar 08 '13 11:03

Guilherme Longo


2 Answers

An empty space has a character code. Even though it doesn't look like much, it still has a value. So does the character taken from the stream. Comparing the character codes of these values is what produces the output.

like image 190
christopher Avatar answered Oct 25 '22 04:10

christopher


Let's take a gander at the language specification (the algorithm itself is described in here) (do note that it defines <, but the > operator simply flips the resulting value).

What the operator does is try to convert both operands to primitive types, with a preference for numbers:

2. a. Let py be the result of calling ToPrimitive(y, hint Number).
2. b. Let px be the result of calling ToPrimitive(x, hint Number).

In our case, x === stream.getChar() and y === ' '. Since both of the operands are primitive strings already, that results in the original values (px = x, py = y), and we move on to:

4. Else, both px and py are Strings

Now it does checks to see if any of the operands are prefixes of the other, for example:

'abc' > 'abcd' // false
'foo' > 'foobar' // false

Which is relevant if getChar() results in a space, since the space is a prefix of itself:

' ' > ' ' // false

We move on, to finding the first character in x and y who're on the same position in the strings, but are different characters:

Let k be the smallest nonnegative integer such that the character at position k within px is different from the character at position k within py. (There must be such a k, for neither String is a prefix of the other.)

(e.g., 'efg' and 'efh', we want g and h)

The characters we've found are then converted to their integer values:

Let m be the integer that is the code unit value for the character at position k within px.
Let n be the integer that is the code unit value for the character at position k within py.

And finally, a comparison is made:

If m < n, return true. Otherwise, return false.

And that's how it's compared to the space.


tl;dr It converts both arguments to their code-unit integer representations, and compares that.

like image 29
Zirak Avatar answered Oct 25 '22 05:10

Zirak