es.array.slice.js 2.1 KB

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