Skip to content

Instantly share code, notes, and snippets.

@tjinlag
Last active October 14, 2021 18:31
Show Gist options
  • Save tjinlag/aba8a3eebe68102d8ec5730451eab143 to your computer and use it in GitHub Desktop.
Save tjinlag/aba8a3eebe68102d8ec5730451eab143 to your computer and use it in GitHub Desktop.
The implementation of reduceRight function in JavaScript by for loop
Array.prototype.reduceRightFunc = function(callbackFn, initialValue) {
let accumulator = initialValue, index = this.length - 1;
if (initialValue === undefined) {
if (!this.length) {
throw new TypeError("Reduce of empty array with no initial value");
} else {
accumulator = this[this.length - 1];
index = this.length - 2;
}
}
for (; index >= 0; index--) {
accumulator = callbackFn(accumulator, this[index], index, this);
}
return accumulator;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment