array-group-to-map.js 1.2 KB

1234567891011121314151617181920212223242526272829303132
  1. 'use strict';
  2. var getBuiltIn = require('../internals/get-built-in');
  3. var bind = require('../internals/function-bind-context');
  4. var uncurryThis = require('../internals/function-uncurry-this');
  5. var IndexedObject = require('../internals/indexed-object');
  6. var toObject = require('../internals/to-object');
  7. var lengthOfArrayLike = require('../internals/length-of-array-like');
  8. var Map = getBuiltIn('Map');
  9. var MapPrototype = Map.prototype;
  10. var mapGet = uncurryThis(MapPrototype.get);
  11. var mapHas = uncurryThis(MapPrototype.has);
  12. var mapSet = uncurryThis(MapPrototype.set);
  13. var push = uncurryThis([].push);
  14. // `Array.prototype.groupToMap` method
  15. // https://github.com/tc39/proposal-array-grouping
  16. module.exports = function groupToMap(callbackfn /* , thisArg */) {
  17. var O = toObject(this);
  18. var self = IndexedObject(O);
  19. var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined);
  20. var map = new Map();
  21. var length = lengthOfArrayLike(self);
  22. var index = 0;
  23. var key, value;
  24. for (;length > index; index++) {
  25. value = self[index];
  26. key = boundFunction(value, index, O);
  27. if (mapHas(map, key)) push(mapGet(map, key), value);
  28. else mapSet(map, key, [value]);
  29. } return map;
  30. };