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