Surprises in Array.prototype.sort()

If you are developing for evergreen browsers, you are a happy developer. You will always have recent browser to work with, latest APIs and more or less stable and predictable behaviour. But when are developing software for some legacy browser, you may run into some weird surprises.

In Merim where I work, we are developing both software and hardware for restaurants. Mostly for the big brands like BurgerKing, McDonalds, Steak-n-shake and others. And for historical reasons some of those devices are running embedded Chromium wrapped in a Python package. It would be a long story if I wanted to explaing why it works this way, but to make it short: we inherited that.

Because there is embedded Chromium tied to a specific Python package, it is no longer evergreen browser. We are stuck at version 49, that version comes from year 2016, so some of the internal APIs and behaviour are not what you would expect in 2022. Like for instance the behaviour of Array.prototype.sort().

Surprise

One would naturally expect that calling myArray.sort(customSortingFunction) will return the exact same results everywhere. But it does not. At least now it does, because the behaviour stabilized in Ecmascript 2019, stating that in case of “item equality” the original sorting order is preserved. Our Chromium is from 2016, so it does not preserve the original sorting order, and we ended with really weird situations, when the same code with same input data worked on developer’s machines, but did worked differently in production.

Solution?

The obvious advice would be to upgrade to recent version of Chromium. Can’t do that, been there, tried that, did not work. So? What to do instead? Well, you have to use some independent algorithm quaranteed to work the same everywhere no matter what. So not relying on browser APIs, but reverting to good old bubbleSort. And honestly, this is the first time I have ever used that in production code.

Algoritms like bubbleSort, quickSort or whatever else esoteric stuff meant to scare newbees can be actually used sometimes 🙂

Exactly …