es.object.group-by.js 1.1 KB

123456789101112131415161718192021222324252627282930
  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 create = getBuiltIn('Object', 'create');
  10. var push = uncurryThis([].push);
  11. // `Object.groupBy` method
  12. // https://github.com/tc39/proposal-array-grouping
  13. $({ target: 'Object', stat: true }, {
  14. groupBy: function groupBy(items, callbackfn) {
  15. requireObjectCoercible(items);
  16. aCallable(callbackfn);
  17. var obj = create(null);
  18. var k = 0;
  19. iterate(items, function (value) {
  20. var key = toPropertyKey(callbackfn(value, k++));
  21. // in some IE versions, `hasOwnProperty` returns incorrect result on integer keys
  22. // but since it's a `null` prototype object, we can safely use `in`
  23. if (key in obj) push(obj[key], value);
  24. else obj[key] = [value];
  25. });
  26. return obj;
  27. }
  28. });