ArraySpeciesCreate.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $species = GetIntrinsic('%Symbol.species%', true);
  4. var $TypeError = GetIntrinsic('%TypeError%');
  5. var ArrayCreate = require('./ArrayCreate');
  6. var Get = require('./Get');
  7. var IsArray = require('./IsArray');
  8. var IsConstructor = require('./IsConstructor');
  9. var IsIntegralNumber = require('./IsIntegralNumber');
  10. var Type = require('./Type');
  11. // https://ecma-international.org/ecma-262/12.0/#sec-arrayspeciescreate
  12. module.exports = function ArraySpeciesCreate(originalArray, length) {
  13. if (!IsIntegralNumber(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. };