esnext.map.reduce.js 1.1 KB

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