AddEntriesFromIterable.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. var inspect = require('object-inspect');
  3. var $TypeError = require('es-errors/type');
  4. var Call = require('./Call');
  5. var Get = require('./Get');
  6. var GetIterator = require('./GetIterator');
  7. var IsCallable = require('./IsCallable');
  8. var IteratorClose = require('./IteratorClose');
  9. var IteratorStep = require('./IteratorStep');
  10. var IteratorValue = require('./IteratorValue');
  11. var ThrowCompletion = require('./ThrowCompletion');
  12. var Type = require('./Type');
  13. // https://262.ecma-international.org/14.0/#sec-add-entries-from-iterable
  14. module.exports = function AddEntriesFromIterable(target, iterable, adder) {
  15. if (!IsCallable(adder)) {
  16. throw new $TypeError('Assertion failed: `adder` is not callable');
  17. }
  18. if (iterable == null) {
  19. throw new $TypeError('Assertion failed: `iterable` is present, and not nullish');
  20. }
  21. var iteratorRecord = GetIterator(iterable, 'sync');
  22. while (true) { // eslint-disable-line no-constant-condition
  23. var next = IteratorStep(iteratorRecord);
  24. if (!next) {
  25. return target;
  26. }
  27. var nextItem = IteratorValue(next);
  28. if (Type(nextItem) !== 'Object') {
  29. var error = ThrowCompletion(new $TypeError('iterator next must return an Object, got ' + inspect(nextItem)));
  30. return IteratorClose(iteratorRecord, error);
  31. }
  32. try {
  33. var k = Get(nextItem, '0');
  34. var v = Get(nextItem, '1');
  35. Call(adder, target, [k, v]);
  36. } catch (e) {
  37. return IteratorClose(iteratorRecord, ThrowCompletion(e));
  38. }
  39. }
  40. };