es.object.group-by.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. // 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. // https://bugs.webkit.org/show_bug.cgi?id=271524
  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. // `Object.groupBy` method
  22. // https://tc39.es/ecma262/#sec-object.groupby
  23. $({ target: 'Object', stat: true, forced: DOES_NOT_WORK_WITH_PRIMITIVES }, {
  24. groupBy: function groupBy(items, callbackfn) {
  25. requireObjectCoercible(items);
  26. aCallable(callbackfn);
  27. var obj = create(null);
  28. var k = 0;
  29. iterate(items, function (value) {
  30. var key = toPropertyKey(callbackfn(value, k++));
  31. // in some IE versions, `hasOwnProperty` returns incorrect result on integer keys
  32. // but since it's a `null` prototype object, we can safely use `in`
  33. if (key in obj) push(obj[key], value);
  34. else createProperty(obj, key, [value]);
  35. });
  36. return obj;
  37. }
  38. });