2 var $ = require('../internals/export');
3 var uncurryThis = require('../internals/function-uncurry-this');
4 var aCallable = require('../internals/a-callable');
5 var toObject = require('../internals/to-object');
6 var lengthOfArrayLike = require('../internals/length-of-array-like');
7 var toString = require('../internals/to-string');
8 var fails = require('../internals/fails');
9 var internalSort = require('../internals/array-sort');
10 var arrayMethodIsStrict = require('../internals/array-method-is-strict');
11 var FF = require('../internals/engine-ff-version');
12 var IE_OR_EDGE = require('../internals/engine-is-ie-or-edge');
13 var V8 = require('../internals/engine-v8-version');
14 var WEBKIT = require('../internals/engine-webkit-version');
17 var un$Sort = uncurryThis(test.sort);
18 var push = uncurryThis(test.push);
21 var FAILS_ON_UNDEFINED = fails(function () {
25 var FAILS_ON_NULL = fails(function () {
29 var STRICT_METHOD = arrayMethodIsStrict('sort');
31 var STABLE_SORT = !fails(function () {
32 // feature detection can be too slow, so check engines versions
33 if (V8) return V8 < 70;
34 if (FF && FF > 3) return;
35 if (IE_OR_EDGE) return true;
36 if (WEBKIT) return WEBKIT < 603;
39 var code, chr, value, index;
41 // generate an array with more 512 elements (Chakra and old V8 fails only in this case)
42 for (code = 65; code < 76; code++) {
43 chr = String.fromCharCode(code);
46 case 66: case 69: case 70: case 72: value = 3; break;
47 case 68: case 71: value = 4; break;
51 for (index = 0; index < 47; index++) {
52 test.push({ k: chr + index, v: value });
56 test.sort(function (a, b) { return b.v - a.v; });
58 for (index = 0; index < test.length; index++) {
59 chr = test[index].k.charAt(0);
60 if (result.charAt(result.length - 1) !== chr) result += chr;
63 return result !== 'DGBEFHACIJK';
66 var FORCED = FAILS_ON_UNDEFINED || !FAILS_ON_NULL || !STRICT_METHOD || !STABLE_SORT;
68 var getSortCompare = function (comparefn) {
69 return function (x, y) {
70 if (y === undefined) return -1;
71 if (x === undefined) return 1;
72 if (comparefn !== undefined) return +comparefn(x, y) || 0;
73 return toString(x) > toString(y) ? 1 : -1;
77 // `Array.prototype.sort` method
78 // https://tc39.es/ecma262/#sec-array.prototype.sort
79 $({ target: 'Array', proto: true, forced: FORCED }, {
80 sort: function sort(comparefn) {
81 if (comparefn !== undefined) aCallable(comparefn);
83 var array = toObject(this);
85 if (STABLE_SORT) return comparefn === undefined ? un$Sort(array) : un$Sort(array, comparefn);
88 var arrayLength = lengthOfArrayLike(array);
89 var itemsLength, index;
91 for (index = 0; index < arrayLength; index++) {
92 if (index in array) push(items, array[index]);
95 internalSort(items, getSortCompare(comparefn));
97 itemsLength = items.length;
100 while (index < itemsLength) array[index] = items[index++];
101 while (index < arrayLength) delete array[index++];