1 | 'use strict';
|
---|
2 | var $ = require('../internals/export');
|
---|
3 | var getBuiltIn = require('../internals/get-built-in');
|
---|
4 | var uncurryThis = require('../internals/function-uncurry-this');
|
---|
5 | var aCallable = require('../internals/a-callable');
|
---|
6 | var requireObjectCoercible = require('../internals/require-object-coercible');
|
---|
7 | var toPropertyKey = require('../internals/to-property-key');
|
---|
8 | var iterate = require('../internals/iterate');
|
---|
9 | var fails = require('../internals/fails');
|
---|
10 |
|
---|
11 | // eslint-disable-next-line es/no-object-groupby -- testing
|
---|
12 | var nativeGroupBy = Object.groupBy;
|
---|
13 | var create = getBuiltIn('Object', 'create');
|
---|
14 | var push = uncurryThis([].push);
|
---|
15 |
|
---|
16 | var DOES_NOT_WORK_WITH_PRIMITIVES = !nativeGroupBy || fails(function () {
|
---|
17 | return nativeGroupBy('ab', function (it) {
|
---|
18 | return it;
|
---|
19 | }).a.length !== 1;
|
---|
20 | });
|
---|
21 |
|
---|
22 | // `Object.groupBy` method
|
---|
23 | // https://tc39.es/ecma262/#sec-object.groupby
|
---|
24 | $({ target: 'Object', stat: true, forced: DOES_NOT_WORK_WITH_PRIMITIVES }, {
|
---|
25 | groupBy: function groupBy(items, callbackfn) {
|
---|
26 | requireObjectCoercible(items);
|
---|
27 | aCallable(callbackfn);
|
---|
28 | var obj = create(null);
|
---|
29 | var k = 0;
|
---|
30 | iterate(items, function (value) {
|
---|
31 | var key = toPropertyKey(callbackfn(value, k++));
|
---|
32 | // in some IE versions, `hasOwnProperty` returns incorrect result on integer keys
|
---|
33 | // but since it's a `null` prototype object, we can safely use `in`
|
---|
34 | if (key in obj) push(obj[key], value);
|
---|
35 | else obj[key] = [value];
|
---|
36 | });
|
---|
37 | return obj;
|
---|
38 | }
|
---|
39 | });
|
---|