-
-
Save sethschori/f240f02352125771c5920c1adfba6ce4 to your computer and use it in GitHub Desktop.
https://repl.it/CgPs/30 created by sethopia
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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'} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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