esnext.map.group-by.js 1.0 KB

12345678910111213141516171819202122232425262728
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var call = require('../internals/function-call');
  4. var uncurryThis = require('../internals/function-uncurry-this');
  5. var aCallable = require('../internals/a-callable');
  6. var getIterator = require('../internals/get-iterator');
  7. var iterate = require('../internals/iterate');
  8. var push = uncurryThis([].push);
  9. // `Map.groupBy` method
  10. // https://github.com/tc39/proposal-collection-methods
  11. $({ target: 'Map', stat: true, forced: true }, {
  12. groupBy: function groupBy(iterable, keyDerivative) {
  13. aCallable(keyDerivative);
  14. var iterator = getIterator(iterable);
  15. var newMap = new this();
  16. var has = aCallable(newMap.has);
  17. var get = aCallable(newMap.get);
  18. var set = aCallable(newMap.set);
  19. iterate(iterator, function (element) {
  20. var derivedKey = keyDerivative(element);
  21. if (!call(has, newMap, derivedKey)) call(set, newMap, derivedKey, [element]);
  22. else push(call(get, newMap, derivedKey), element);
  23. }, { IS_ITERATOR: true });
  24. return newMap;
  25. }
  26. });