esnext.map.reduce.js 928 B

12345678910111213141516171819202122232425262728
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var aCallable = require('../internals/a-callable');
  4. var aMap = require('../internals/a-map');
  5. var iterate = require('../internals/map-iterate');
  6. var $TypeError = TypeError;
  7. // `Map.prototype.reduce` method
  8. // https://github.com/tc39/proposal-collection-methods
  9. $({ target: 'Map', proto: true, real: true, forced: true }, {
  10. reduce: function reduce(callbackfn /* , initialValue */) {
  11. var map = aMap(this);
  12. var noInitial = arguments.length < 2;
  13. var accumulator = noInitial ? undefined : arguments[1];
  14. aCallable(callbackfn);
  15. iterate(map, function (value, key) {
  16. if (noInitial) {
  17. noInitial = false;
  18. accumulator = value;
  19. } else {
  20. accumulator = callbackfn(accumulator, value, key, map);
  21. }
  22. });
  23. if (noInitial) throw new $TypeError('Reduce of empty map with no initial value');
  24. return accumulator;
  25. }
  26. });