ArraySpeciesCreate.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $species = GetIntrinsic('%Symbol.species%', true);
  4. var $TypeError = require('es-errors/type');
  5. var ArrayCreate = require('./ArrayCreate');
  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/12.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 isArray = IsArray(originalArray);
  17. if (!isArray) {
  18. return ArrayCreate(length);
  19. }
  20. var 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. if (typeof C === 'undefined') {
  33. return ArrayCreate(length);
  34. }
  35. if (!IsConstructor(C)) {
  36. throw new $TypeError('C must be a constructor');
  37. }
  38. return new C(length); // Construct(C, length);
  39. };