Created
September 8, 2018 06:37
-
-
Save mfalade/499d7106ce281053b14ffc405ca5d401 to your computer and use it in GitHub Desktop.
A basic implementation of the Array.prototype.reduce method
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
Array.prototype.xreduce = myReduce; | |
function myReduce (action, defaultValue) { | |
var result = []; | |
var isObject = typeof defaultValue === 'object'; | |
var initialAccVal = isObject ? (defaultValue.constructor === Object ? {} : []) : defaultValue; | |
var acc = isObject ? Object.assign(initialAccVal, defaultValue) : defaultValue; | |
for (var i = 0; i < this.length; i++) { | |
var args = [acc, this[i], i, this]; | |
acc = action.apply(null, args); | |
} | |
return acc; | |
} | |
var res = [1, 2, 3].xreduce((acc, value, index, array) => { | |
acc.push(value + 4); | |
return acc; | |
}, []); | |
console.log(res, 'reduce output') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment