CreateListFromArrayLike.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. // https://ecma-international.org/ecma-262/6.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 = ToLength(Get(obj, 'length'));
  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. };