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