CreateListFromArrayLike.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 ToLength = require('./ToLength');
  10. var ToString = require('./ToString');
  11. var Type = require('./Type');
  12. var defaultElementTypes = ['Undefined', 'Null', 'Boolean', 'String', 'Symbol', 'Number', 'Object'];
  13. // https://262.ecma-international.org/6.0/#sec-createlistfromarraylike
  14. module.exports = function CreateListFromArrayLike(obj) {
  15. var elementTypes = arguments.length > 1
  16. ? arguments[1]
  17. : defaultElementTypes;
  18. if (Type(obj) !== 'Object') {
  19. throw new $TypeError('Assertion failed: `obj` must be an Object');
  20. }
  21. if (!IsArray(elementTypes)) {
  22. throw new $TypeError('Assertion failed: `elementTypes`, if provided, must be an array');
  23. }
  24. var len = ToLength(Get(obj, 'length'));
  25. var list = [];
  26. var index = 0;
  27. while (index < len) {
  28. var indexName = ToString(index);
  29. var next = Get(obj, indexName);
  30. var nextType = Type(next);
  31. if ($indexOf(elementTypes, nextType) < 0) {
  32. throw new $TypeError('item type ' + nextType + ' is not a valid elementType');
  33. }
  34. $push(list, next);
  35. index += 1;
  36. }
  37. return list;
  38. };