implementation.js 1.9 KB

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