implementation.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. var Call = require('es-abstract/2021/Call');
  3. var Get = require('es-abstract/2021/Get');
  4. var HasProperty = require('es-abstract/2021/HasProperty');
  5. var IsCallable = require('es-abstract/2021/IsCallable');
  6. var LengthOfArrayLike = require('es-abstract/2021/LengthOfArrayLike');
  7. var ToObject = require('es-abstract/2021/ToObject');
  8. var ToString = require('es-abstract/2021/ToString');
  9. var callBound = require('call-bind/callBound');
  10. var isString = require('is-string');
  11. var $TypeError = TypeError;
  12. // Check failure of by-index access of string characters (IE < 9) and failure of `0 in boxedString` (Rhino)
  13. var boxedString = Object('a');
  14. var splitString = boxedString[0] !== 'a' || !(0 in boxedString);
  15. var strSplit = callBound('%String.prototype.split%');
  16. module.exports = function reduce(callbackfn) {
  17. var O = ToObject(this);
  18. var self = splitString && isString(O) ? strSplit(O, '') : O;
  19. var len = LengthOfArrayLike(self);
  20. // If no callback function or if callback is not a callable function
  21. if (!IsCallable(callbackfn)) {
  22. throw new $TypeError('Array.prototype.reduce callback must be a function');
  23. }
  24. if (len === 0 && arguments.length < 2) {
  25. throw new $TypeError('reduce of empty array with no initial value');
  26. }
  27. var k = 0;
  28. var accumulator;
  29. var Pk, kPresent;
  30. if (arguments.length > 1) {
  31. accumulator = arguments[1];
  32. } else {
  33. kPresent = false;
  34. while (!kPresent && k < len) {
  35. Pk = ToString(k);
  36. kPresent = HasProperty(O, Pk);
  37. if (kPresent) {
  38. accumulator = Get(O, Pk);
  39. }
  40. k += 1;
  41. }
  42. if (!kPresent) {
  43. throw new $TypeError('reduce of empty array with no initial value');
  44. }
  45. }
  46. while (k < len) {
  47. Pk = ToString(k);
  48. kPresent = HasProperty(O, Pk);
  49. if (kPresent) {
  50. var kValue = Get(O, Pk);
  51. accumulator = Call(callbackfn, void undefined, [accumulator, kValue, k, O]);
  52. }
  53. k += 1;
  54. }
  55. return accumulator;
  56. };