es.array.slice.js 2.1 KB

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