esnext.map.reduce.js 1.1 KB

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