Skip to content

test: use a valid comparefn for sort

According the the ES spec a valid comparefn returns a negative number, zero, or a positive number. The behavior of returning a boolean is also not consistent among JS engines.

For example:

$ eshost -ise "Object.keys({ a200: 4, a100: 1, a102: 3, a101: 2 }).sort(function (a, b) { return a < b; })"
## Source
print(Object.keys({ a200: 4, a100: 1, a102: 3, a101: 2 }).sort(function (a, b) { return a < b; }))

#### Chakra, V8, V8 --harmony
a200,a100,a102,a101

#### JavaScriptCore, SpiderMonkey, XS
a200,a102,a101,a100

Interestingly D8 and node-v8 disagree (EDIT: this is because of the Timsort introduction in V8 7.0):

$ ~/.jsvu/v8 -e "console.log(Object.keys({ a200: 4, a100: 1, a102: 3, a101: 2 }).sort(function (a, b) { return a < b; }))"
a200,a100,a102,a101
$ node -e "console.log(Object.keys({ a200: 4, a100: 1, a102: 3, a101: 2 }).sort(function (a, b) { return a < b; }))"
[ 'a200', 'a102', 'a101', 'a100' ]

With the updated compare function everyone agrees:

$ eshost -ise "Object.keys({ a200: 4, a100: 1, a102: 3, a101: 2 }).sort(function (a, b) { return a === b ? 0 : (a < b ? 1 : -1); })"
## Source
print(Object.keys({ a200: 4, a100: 1, a102: 3, a101: 2 }).sort(function (a, b) { return a === b ? 0 : (a < b ? 1 : -1); }))

#### Chakra, JavaScriptCore, SpiderMonkey, V8, V8 --harmony, XS
a200,a102,a101,a100
Checklist
  • make -j4 test (UNIX), or vcbuild test (Windows) passes
  • tests and/or benchmarks are included
  • documentation is changed or added
  • commit message follows commit guidelines

Merge request reports

Loading