Does Javascript use SpiderMonkey 31.2 and work good?

I’ve solved a puzzle, but had only 90%. (lost one of the achievements)
It’s because of using Array.sort() function.
What’s happened:
there was an array after reading input with parseInt(readline()). So it should be an array of integers.
But seems it isn’t!
And sort function does lexical sort. (I’ve noticed it once in clash of code, but there was a timed challenge and I didn’t research the reason of problem)
I tried the sort function in sandboxed SpiderMonkey engine and there the sort function works good.

But here in IDE we MUST use
sort( function(a,b) { return Number(a)<Number(b)?-1:1 } )
or so…

I’ve no found a JS engine (from the latest used in browsers) that behaves same way.
Everywhere sort() works good, but not in Codingames =((

I just press F12 on Firefox (latest version) and i execute this code:

[-1, 10, 2, 1].sort()

The result is

[-1, 1, 10, 2]

I don’t know what do you mean by “everywhere”, but it’s look like Firefox and Chrome are not included.

In javascript, parseInt will just parse the first integer if you have a string like 1 2 3 4 5. You have to use .split(' '). And if you want to have a numeric sort, you have to write .sort((a,b)=>a-b).

2 Likes

If you want to read a list of integers from inputs, you should replace parseInt(readline()) with something like readline().split(' ').map(Number).
Sorting works as intended then.

Thx, Magus.
I can’t continue discussion because at work I’ve tested on desktop PC and got same results with you. Maybe it is strange behavior of my own laptop… (But do you believe that I could just wrote a post without testing or so?)

And thx, all about split, parse and custom sort functions is known for me) And the question wasn’t about it… But maybe it would be useful for someone who come here…

Thx, Djoums

Post is closed till i reproduce it again…

(try those in chromium console)
parseInt(“5”) -> 5
parseInt("[5 6 -1 12]") -> NaN
readline() return a string (the line read), so the first readline() in just to read N: the size of the array (which is an integer) so parseInt(readline()) while return ONE number. Doing readline.split(' ') afterwards just change “5 6 -1 12” (return of readline) into [“5”, “6”, “-1”, “12”] so the numbers are still strings. That’s completely normal

If you don’t believe me try this code in the chromium console:

"5 6 -1 12".split(' ')

Of course, split will return array of strings!
parseInt will return integer as it written in js reference at MDN


Guys, I see that reproduction is unstable. I don’t know how I did it yesterday. Maybe there was a framework that overrides JS. Now there is no problem and reason to discuss!
Now there is only problem - there isn’t a button(or I don’t see it) 'Close post" for the author of post.