CreateListFromArrayLike.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. var callBound = require('call-bind/callBound');
  3. var $TypeError = require('es-errors/type');
  4. var $indexOf = callBound('Array.prototype.indexOf', true) || callBound('String.prototype.indexOf');
  5. var $push = callBound('Array.prototype.push');
  6. var Get = require('./Get');
  7. var IsArray = require('./IsArray');
  8. var ToLength = require('./ToLength');
  9. var ToString = require('./ToString');
  10. var Type = require('./Type');
  11. var defaultElementTypes = ['Undefined', 'Null', 'Boolean', 'String', 'Symbol', 'Number', 'Object'];
  12. // https://262.ecma-international.org/6.0/#sec-createlistfromarraylike
  13. module.exports = function CreateListFromArrayLike(obj) {
  14. var elementTypes = arguments.length > 1
  15. ? arguments[1]
  16. : defaultElementTypes;
  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. };