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