• 0

Implement reduce in javascript

Reducing an array to a single value

Often we have to iterate over the array by accessing multiple items at a time. For example, if you have to find the largest element in an array, then you have to keep track of the largest value in a closure while iterating over it. This behavior can be abstracted using Array.prototype.reduce().

This post is a follow up post of the
- Getting started Functional Programming in JavaScript. I would recommend reading that post first.

Problem

Find the maximum element in the given array

Let's solve with Array.prototype.forEach()


'use strict';
function reduce() {
var boxarts = [{
width: 200,
height: 200
}, {
width: 150,
height: 200
}, {
width: 300,
height: 200
}, {
width: 425,
height: 150
}],
currentSize,
maxSize = -1,
largestBoxart;
boxarts.forEach(function(boxart) {
currentSize = boxart.width * boxart.height;
if (currentSize > maxSize) {
largestBoxart = boxart;
maxSize = currentSize;
}
});
return largestBoxart;
}
console.log(reduce()); // {width: 425, height: 150}
view raw reduce-1.js hosted with ❤ by GitHub

Implement Array.prototype.reduce() using Array.prototype.forEach().


'use strict';
Array.prototype.reduce = function(callback, initialValue) {
let counter;
let accumulatedValue;
if (this.length === 0) {
return this;
} else {
if (arguments.length === 1) {
counter = 1;
accumulatedValue = this[0];
} else if (arguments.length == 2) {
counter = 0;
accumulatedValue = initialValue;
} else {
throw 'Invalid number of arguments were passed.'
}
}
while (counter < this.length) {
accumulatedValue = callback(accumulatedValue, this[counter]);
counter++;
}
return [accumulatedValue];
};
console.log([1, 2, 3].reduce(function(p, c) {
return p + c;
})); // [6]
console.log([1, 2, 3, 4, 5].reduce(function(p, c) {
return p > c ? p : c;
})); // [5]
var boxarts = [
{ width: 200, height:200 },
{ width: 150, height:200 },
{ width: 300, height:200 },
{ width: 425, height:150 }
];
console.log(boxarts.reduce(function(p, c) {
return p.width * p.height > c.width * c.height ? p : c;
})); // [{height: 150, width: 425}]
view raw reduce-2.js hosted with ❤ by GitHub

Further Reading