UNPKG

2.46 kBJavaScriptView Raw
1'use strict';
2var global = require('../internals/global');
3var uncurryThis = require('../internals/function-uncurry-this-clause');
4var fails = require('../internals/fails');
5var aCallable = require('../internals/a-callable');
6var internalSort = require('../internals/array-sort');
7var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
8var FF = require('../internals/engine-ff-version');
9var IE_OR_EDGE = require('../internals/engine-is-ie-or-edge');
10var V8 = require('../internals/engine-v8-version');
11var WEBKIT = require('../internals/engine-webkit-version');
12
13var aTypedArray = ArrayBufferViewCore.aTypedArray;
14var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
15var Uint16Array = global.Uint16Array;
16var nativeSort = Uint16Array && uncurryThis(Uint16Array.prototype.sort);
17
18// WebKit
19var ACCEPT_INCORRECT_ARGUMENTS = !!nativeSort && !(fails(function () {
20 nativeSort(new Uint16Array(2), null);
21}) && fails(function () {
22 nativeSort(new Uint16Array(2), {});
23}));
24
25var STABLE_SORT = !!nativeSort && !fails(function () {
26 // feature detection can be too slow, so check engines versions
27 if (V8) return V8 < 74;
28 if (FF) return FF < 67;
29 if (IE_OR_EDGE) return true;
30 if (WEBKIT) return WEBKIT < 602;
31
32 var array = new Uint16Array(516);
33 var expected = Array(516);
34 var index, mod;
35
36 for (index = 0; index < 516; index++) {
37 mod = index % 4;
38 array[index] = 515 - index;
39 expected[index] = index - 2 * mod + 3;
40 }
41
42 nativeSort(array, function (a, b) {
43 return (a / 4 | 0) - (b / 4 | 0);
44 });
45
46 for (index = 0; index < 516; index++) {
47 if (array[index] !== expected[index]) return true;
48 }
49});
50
51var getSortCompare = function (comparefn) {
52 return function (x, y) {
53 if (comparefn !== undefined) return +comparefn(x, y) || 0;
54 // eslint-disable-next-line no-self-compare -- NaN check
55 if (y !== y) return -1;
56 // eslint-disable-next-line no-self-compare -- NaN check
57 if (x !== x) return 1;
58 if (x === 0 && y === 0) return 1 / x > 0 && 1 / y < 0 ? 1 : -1;
59 return x > y;
60 };
61};
62
63// `%TypedArray%.prototype.sort` method
64// https://tc39.es/ecma262/#sec-%typedarray%.prototype.sort
65exportTypedArrayMethod('sort', function sort(comparefn) {
66 if (comparefn !== undefined) aCallable(comparefn);
67 if (STABLE_SORT) return nativeSort(this, comparefn);
68
69 return internalSort(aTypedArray(this), getSortCompare(comparefn));
70}, !STABLE_SORT || ACCEPT_INCORRECT_ARGUMENTS);