esnext.map.group-by.js 1.0 KB

1234567891011121314151617181920212223242526272829
  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 isCallable = require('../internals/is-callable');
  6. var aCallable = require('../internals/a-callable');
  7. var iterate = require('../internals/iterate');
  8. var Map = require('../internals/map-helpers').Map;
  9. var push = uncurryThis([].push);
  10. // `Map.groupBy` method
  11. // https://github.com/tc39/proposal-collection-methods
  12. $({ target: 'Map', stat: true, forced: true }, {
  13. groupBy: function groupBy(iterable, keyDerivative) {
  14. var C = isCallable(this) ? this : Map;
  15. var newMap = new C();
  16. aCallable(keyDerivative);
  17. var has = aCallable(newMap.has);
  18. var get = aCallable(newMap.get);
  19. var set = aCallable(newMap.set);
  20. iterate(iterable, function (element) {
  21. var derivedKey = keyDerivative(element);
  22. if (!call(has, newMap, derivedKey)) call(set, newMap, derivedKey, [element]);
  23. else push(call(get, newMap, derivedKey), element);
  24. });
  25. return newMap;
  26. }
  27. });