Skip to content

Instantly share code, notes, and snippets.

Created July 31, 2016 19:51
Show Gist options
  • Save anonymous/7381dd2de1c94db3c3f2f98d1cfac49d to your computer and use it in GitHub Desktop.
Save anonymous/7381dd2de1c94db3c3f2f98d1cfac49d to your computer and use it in GitHub Desktop.
https://repl.it/CgPs/30 created by sethopia
// Attach a method to the Array prototype called myReduce.
// It should be utilized and perform exactly as Array.prototype.reduce does. Use the code snippet below as a guide.
Array.prototype.myReduce = function(callback, initVal) {
var startingIndex = 0;
var returnVal;
if (!initVal) {
startingIndex = 1;
returnVal = this[0];
} else {
returnVal = initVal;
}
for (var i = startingIndex; i < this.length; i++) {
returnVal = callback(returnVal,this[i],i,this);
}
return returnVal;
}
function add(prev, current) {
return prev + current;
}
var arr = [1,2,3,4,5];
var sum = arr.myReduce(add, 0);
console.log(sum); // 15
function buildObject(prev, current) {
prev[current] = current.charAt(0).toUpperCase() + current.slice(1);
return prev;
}
var arr2 = ['cat', 'dog', 'fish'];
var obj = arr2.myReduce(buildObject, {});
console.log(obj); // { cat: 'Cat', dog: 'Dog', fish: 'Fish'}
Native Browser JavaScript
>>> 15
{ cat: 'Cat', dog: 'Dog', fish: 'Fish' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment