esnext.array.group-by-to-map.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var getBuiltIn = require('../internals/get-built-in');
  4. var bind = require('../internals/function-bind-context');
  5. var uncurryThis = require('../internals/function-uncurry-this');
  6. var IndexedObject = require('../internals/indexed-object');
  7. var toObject = require('../internals/to-object');
  8. var lengthOfArrayLike = require('../internals/length-of-array-like');
  9. var arrayMethodIsStrict = require('../internals/array-method-is-strict');
  10. var addToUnscopables = require('../internals/add-to-unscopables');
  11. var Map = getBuiltIn('Map');
  12. var MapPrototype = Map.prototype;
  13. var mapGet = uncurryThis(MapPrototype.get);
  14. var mapHas = uncurryThis(MapPrototype.has);
  15. var mapSet = uncurryThis(MapPrototype.set);
  16. var push = uncurryThis([].push);
  17. // `Array.prototype.groupByToMap` method
  18. // https://github.com/tc39/proposal-array-grouping
  19. // https://bugs.webkit.org/show_bug.cgi?id=236541
  20. $({ target: 'Array', proto: true, forced: !arrayMethodIsStrict('groupByToMap') }, {
  21. groupByToMap: function groupByToMap(callbackfn /* , thisArg */) {
  22. var O = toObject(this);
  23. var self = IndexedObject(O);
  24. var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined);
  25. var map = new Map();
  26. var length = lengthOfArrayLike(self);
  27. var index = 0;
  28. var key, value;
  29. for (;length > index; index++) {
  30. value = self[index];
  31. key = boundFunction(value, index, O);
  32. if (mapHas(map, key)) push(mapGet(map, key), value);
  33. else mapSet(map, key, [value]);
  34. } return map;
  35. }
  36. });
  37. addToUnscopables('groupByToMap');