es.object.group-by.js 1.5 KB

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