AddValueToKeyedGroup.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. 'use strict';
  2. var $TypeError = require('es-errors/type');
  3. var callBound = require('call-bind/callBound');
  4. var $push = callBound('Array.prototype.push');
  5. var SameValue = require('./SameValue');
  6. var IsArray = require('../helpers/IsArray');
  7. var every = require('../helpers/every');
  8. var forEach = require('../helpers/forEach');
  9. var hasOwn = require('hasown');
  10. var isKeyedGroup = function (group) {
  11. return hasOwn(group, '[[Key]]')
  12. && hasOwn(group, '[[Elements]]')
  13. && IsArray(group['[[Elements]]']);
  14. };
  15. // https://tc39.es/ecma262/#sec-add-value-to-keyed-group
  16. module.exports = function AddValueToKeyedGroup(groups, key, value) {
  17. if (!IsArray(groups) || (groups.length > 0 && !every(groups, isKeyedGroup))) {
  18. throw new $TypeError('Assertion failed: `groups` must be a List of Records with [[Key]] and [[Elements]]');
  19. }
  20. var matched = 0;
  21. forEach(groups, function (g) { // step 1
  22. if (SameValue(g['[[Key]]'], key)) { // step 2
  23. matched += 1;
  24. if (matched > 1) {
  25. throw new $TypeError('Assertion failed: Exactly one element of groups meets this criterion'); // step 2.a
  26. }
  27. $push(g['[[Elements]]'], value); // step 2.b
  28. }
  29. });
  30. if (matched === 0) {
  31. var group = { '[[Key]]': key, '[[Elements]]': [value] }; // step 2
  32. $push(groups, group); // step 3
  33. }
  34. };