Javascript Array reduceRight(callback)

Description

Javascript Array reduceRight(callback)


// Array.prototype.reduceRight
Array.prototype.reduceRight = function reduceRight(callback) {
 if (typeof callback !== 'function') {
  throw new TypeError(callback + ' is not a function');
 }

 var array = this, index = array.length - 1, previousValue;

 while (index >= 0 && !(index in array)) {
  --index;//ww  w .j a  v a 2  s  .  co m
 }

 previousValue = 2 in arguments ? arguments[2] : array[index];

 for (--index; index >= 0; --index) {
  if (index in array) {
   previousValue = callback(previousValue, array[index], index, array);
  }
 }

 return previousValue;
};

Javascript Array reduceRight(callback)

Array.prototype.reduceRight = function reduceRight(callback) {
 if (this === undefined || this === null) {
  throw new TypeError(this + ' is not an object');
 }

 if (!(callback instanceof Function)) {
  throw new TypeError(callback + ' is not a function');
 }

 var/*w  ww .ja  v a2 s  .  co m*/
 object = Object(this),
 arraylike = object instanceof String ? object.split('') : object,
 length = -1,
 index = Math.max(Math.min(arraylike.length, 9007199254740991), 0) || 0,
 previousValue;

 if (1 in arguments) {
  previousValue = arguments[1];
 } else {
  while (--index > length && !(index in arraylike)) {}

  if (index <= length) {
   throw new TypeError('Reduce of empty array with no initial value');
  }

  previousValue = arraylike[index];
 }

 while (--index > length) {
  if (index in arraylike) {
   previousValue = callback(previousValue, arraylike[index], index, object);
  }
 }

 return previousValue;
};



PreviousNext

Related