Created
December 17, 2018 06:40
-
-
Save PulkitAgg/c1d4c273a0cb387f42e9ecfcb483d97a to your computer and use it in GitHub Desktop.
Make Own Reducer function in js
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
// Problem: Make your own reducer function in javascript. | |
//Solution: | |
// First Add MyReducer function as prototype in array. | |
Array.prototype.MyReducer = function (fn, init) { | |
let current; | |
let startIndex = 0; | |
// If initial value is not defined assign it to with this first index value. | |
if (init) { | |
current = init; | |
} else { | |
// this refer to the array from which MyReducer is called. | |
current = this[0]; | |
// If already take first index value then start loop from index 1. | |
startIndex = 1; | |
} | |
for (let count = startIndex; count < this.length; count++) { | |
current = fn(this[count], current); | |
} | |
return current; | |
} | |
//Way of calling MyReducer fucntion. | |
[1,2,3,4].MyReducer((a,b) => a+b); // Here 1 will be the initial value. | |
[1,2,3,4].MyReducer((a,b) => a+b, 10); // Here 10 will be the initial value. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment