ArraySpeciesCreate.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $Array = GetIntrinsic('%Array%');
  4. var $species = GetIntrinsic('%Symbol.species%', true);
  5. var $TypeError = require('es-errors/type');
  6. var Get = require('./Get');
  7. var IsArray = require('./IsArray');
  8. var IsConstructor = require('./IsConstructor');
  9. var Type = require('./Type');
  10. var isInteger = require('../helpers/isInteger');
  11. // https://262.ecma-international.org/6.0/#sec-arrayspeciescreate
  12. module.exports = function ArraySpeciesCreate(originalArray, length) {
  13. if (!isInteger(length) || length < 0) {
  14. throw new $TypeError('Assertion failed: length must be an integer >= 0');
  15. }
  16. var len = length === 0 ? 0 : length;
  17. var C;
  18. var isArray = IsArray(originalArray);
  19. if (isArray) {
  20. C = Get(originalArray, 'constructor');
  21. // TODO: figure out how to make a cross-realm normal Array, a same-realm Array
  22. // if (IsConstructor(C)) {
  23. // if C is another realm's Array, C = undefined
  24. // Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Array))) === null ?
  25. // }
  26. if ($species && Type(C) === 'Object') {
  27. C = Get(C, $species);
  28. if (C === null) {
  29. C = void 0;
  30. }
  31. }
  32. }
  33. if (typeof C === 'undefined') {
  34. return $Array(len);
  35. }
  36. if (!IsConstructor(C)) {
  37. throw new $TypeError('C must be a constructor');
  38. }
  39. return new C(len); // Construct(C, len);
  40. };