UNPKG

2.18 kBJavaScriptView Raw
1'use strict';
2var $ = require('../internals/export');
3var isObject = require('../internals/is-object');
4var isArray = require('../internals/is-array');
5var toAbsoluteIndex = require('../internals/to-absolute-index');
6var toLength = require('../internals/to-length');
7var toIndexedObject = require('../internals/to-indexed-object');
8var createProperty = require('../internals/create-property');
9var wellKnownSymbol = require('../internals/well-known-symbol');
10var arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');
11var arrayMethodUsesToLength = require('../internals/array-method-uses-to-length');
12
13var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('slice');
14var USES_TO_LENGTH = arrayMethodUsesToLength('slice', { ACCESSORS: true, 0: 0, 1: 2 });
15
16var SPECIES = wellKnownSymbol('species');
17var nativeSlice = [].slice;
18var max = Math.max;
19
20// `Array.prototype.slice` method
21// https://tc39.es/ecma262/#sec-array.prototype.slice
22// fallback for not array-like ES3 strings and DOM objects
23$({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, {
24 slice: function slice(start, end) {
25 var O = toIndexedObject(this);
26 var length = toLength(O.length);
27 var k = toAbsoluteIndex(start, length);
28 var fin = toAbsoluteIndex(end === undefined ? length : end, length);
29 // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
30 var Constructor, result, n;
31 if (isArray(O)) {
32 Constructor = O.constructor;
33 // cross-realm fallback
34 if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) {
35 Constructor = undefined;
36 } else if (isObject(Constructor)) {
37 Constructor = Constructor[SPECIES];
38 if (Constructor === null) Constructor = undefined;
39 }
40 if (Constructor === Array || Constructor === undefined) {
41 return nativeSlice.call(O, k, fin);
42 }
43 }
44 result = new (Constructor === undefined ? Array : Constructor)(max(fin - k, 0));
45 for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);
46 result.length = n;
47 return result;
48 }
49});