I'm trying to implement reduce() from scratch. I was able to get it working, but how does javascript know what "array" is even though I never defined it anywhere?
function reduce(callback, initialVal) {
var accumulator = (initialVal === undefined) ? undefined : initialVal;
for (var i=0; i<array.length; i++) {
if (accumulator !== undefined) {
accumulator = callback(accumulator, array[i], i, array);
} else {
accumulator = array[i]
}
}
return accumulator;
};
// testing a basic sum
arr = [1,2,3]
arr.reduce( (accumulator, elem) => accumulator+=elem )
EDIT: I got it working :D I Changed 'array' to "this" since I was creating a new method under Array.prototype.
Array.prototype.myReduce = function(callback, initialVal) {
var accumulator = (initialVal !== undefined) ? initialVal : undefined;
for (var i=0; i<this.length; i++) {
if (accumulator !== undefined) {
accumulator = callback(accumulator, this[i], i, this);
} else {
accumulator = this[i]
}
}
return accumulator;
};
arr.myReduce( (accumulator, elem) => accumulator+=elem )
arr.myReduce( (accumulator, elem) => accumulator+=elem , 100)