esnext.map.reduce.js 1.2 KB

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