CreateListFromArrayLike.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var callBound = require('call-bind/callBound');
  4. var $TypeError = GetIntrinsic('%TypeError%');
  5. var $indexOf = callBound('Array.prototype.indexOf', true) || callBound('String.prototype.indexOf');
  6. var $push = callBound('Array.prototype.push');
  7. var Get = require('./Get');
  8. var IsArray = require('./IsArray');
  9. var LengthOfArrayLike = require('./LengthOfArrayLike');
  10. var ToString = require('./ToString');
  11. var Type = require('./Type');
  12. // https://262.ecma-international.org/11.0/#sec-createlistfromarraylike
  13. module.exports = function CreateListFromArrayLike(obj) {
  14. var elementTypes = arguments.length > 1
  15. ? arguments[1]
  16. : ['Undefined', 'Null', 'Boolean', 'String', 'Symbol', 'Number', 'Object'];
  17. if (Type(obj) !== 'Object') {
  18. throw new $TypeError('Assertion failed: `obj` must be an Object');
  19. }
  20. if (!IsArray(elementTypes)) {
  21. throw new $TypeError('Assertion failed: `elementTypes`, if provided, must be an array');
  22. }
  23. var len = LengthOfArrayLike(obj);
  24. var list = [];
  25. var index = 0;
  26. while (index < len) {
  27. var indexName = ToString(index);
  28. var next = Get(obj, indexName);
  29. var nextType = Type(next);
  30. if ($indexOf(elementTypes, nextType) < 0) {
  31. throw new $TypeError('item type ' + nextType + ' is not a valid elementType');
  32. }
  33. $push(list, next);
  34. index += 1;
  35. }
  36. return list;
  37. };