es.map.group-by.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var uncurryThis = require('../internals/function-uncurry-this');
  4. var aCallable = require('../internals/a-callable');
  5. var requireObjectCoercible = require('../internals/require-object-coercible');
  6. var iterate = require('../internals/iterate');
  7. var MapHelpers = require('../internals/map-helpers');
  8. var IS_PURE = require('../internals/is-pure');
  9. var fails = require('../internals/fails');
  10. var Map = MapHelpers.Map;
  11. var has = MapHelpers.has;
  12. var get = MapHelpers.get;
  13. var set = MapHelpers.set;
  14. var push = uncurryThis([].push);
  15. var DOES_NOT_WORK_WITH_PRIMITIVES = IS_PURE || fails(function () {
  16. return Map.groupBy('ab', function (it) {
  17. return it;
  18. }).get('a').length !== 1;
  19. });
  20. // `Map.groupBy` method
  21. // https://tc39.es/ecma262/#sec-map.groupby
  22. $({ target: 'Map', stat: true, forced: IS_PURE || DOES_NOT_WORK_WITH_PRIMITIVES }, {
  23. groupBy: function groupBy(items, callbackfn) {
  24. requireObjectCoercible(items);
  25. aCallable(callbackfn);
  26. var map = new Map();
  27. var k = 0;
  28. iterate(items, function (value) {
  29. var key = callbackfn(value, k++);
  30. if (!has(map, key)) set(map, key, [value]);
  31. else push(get(map, key), value);
  32. });
  33. return map;
  34. }
  35. });