es.array.concat.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var fails = require('../internals/fails');
  4. var isArray = require('../internals/is-array');
  5. var isObject = require('../internals/is-object');
  6. var toObject = require('../internals/to-object');
  7. var lengthOfArrayLike = require('../internals/length-of-array-like');
  8. var doesNotExceedSafeInteger = require('../internals/does-not-exceed-safe-integer');
  9. var createProperty = require('../internals/create-property');
  10. var arraySpeciesCreate = require('../internals/array-species-create');
  11. var arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');
  12. var wellKnownSymbol = require('../internals/well-known-symbol');
  13. var V8_VERSION = require('../internals/environment-v8-version');
  14. var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');
  15. // We can't use this feature detection in V8 since it causes
  16. // deoptimization and serious performance degradation
  17. // https://github.com/zloirock/core-js/issues/679
  18. var IS_CONCAT_SPREADABLE_SUPPORT = V8_VERSION >= 51 || !fails(function () {
  19. var array = [];
  20. array[IS_CONCAT_SPREADABLE] = false;
  21. return array.concat()[0] !== array;
  22. });
  23. var isConcatSpreadable = function (O) {
  24. if (!isObject(O)) return false;
  25. var spreadable = O[IS_CONCAT_SPREADABLE];
  26. return spreadable !== undefined ? !!spreadable : isArray(O);
  27. };
  28. var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !arrayMethodHasSpeciesSupport('concat');
  29. // `Array.prototype.concat` method
  30. // https://tc39.es/ecma262/#sec-array.prototype.concat
  31. // with adding support of @@isConcatSpreadable and @@species
  32. $({ target: 'Array', proto: true, arity: 1, forced: FORCED }, {
  33. // eslint-disable-next-line no-unused-vars -- required for `.length`
  34. concat: function concat(arg) {
  35. var O = toObject(this);
  36. var A = arraySpeciesCreate(O, 0);
  37. var n = 0;
  38. var i, k, length, len, E;
  39. for (i = -1, length = arguments.length; i < length; i++) {
  40. E = i === -1 ? O : arguments[i];
  41. if (isConcatSpreadable(E)) {
  42. len = lengthOfArrayLike(E);
  43. doesNotExceedSafeInteger(n + len);
  44. for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);
  45. } else {
  46. doesNotExceedSafeInteger(n + 1);
  47. createProperty(A, n++, E);
  48. }
  49. }
  50. A.length = n;
  51. return A;
  52. }
  53. });