UNPKG

1.95 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 arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');
10var wellKnownSymbol = require('../internals/well-known-symbol');
11
12var SPECIES = wellKnownSymbol('species');
13var nativeSlice = [].slice;
14var max = Math.max;
15
16// `Array.prototype.slice` method
17// https://tc39.github.io/ecma262/#sec-array.prototype.slice
18// fallback for not array-like ES3 strings and DOM objects
19$({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('slice') }, {
20 slice: function slice(start, end) {
21 var O = toIndexedObject(this);
22 var length = toLength(O.length);
23 var k = toAbsoluteIndex(start, length);
24 var fin = toAbsoluteIndex(end === undefined ? length : end, length);
25 // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
26 var Constructor, result, n;
27 if (isArray(O)) {
28 Constructor = O.constructor;
29 // cross-realm fallback
30 if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) {
31 Constructor = undefined;
32 } else if (isObject(Constructor)) {
33 Constructor = Constructor[SPECIES];
34 if (Constructor === null) Constructor = undefined;
35 }
36 if (Constructor === Array || Constructor === undefined) {
37 return nativeSlice.call(O, k, fin);
38 }
39 }
40 result = new (Constructor === undefined ? Array : Constructor)(max(fin - k, 0));
41 for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);
42 result.length = n;
43 return result;
44 }
45});