polyfills for .forEach(), .map(), .filter() and .reduce()

this-and-bind-in-javascript

My favourite rapper Logic killing the beat on stage.

What is a polyfill?

Polyfill is a piece of code, that developer expects from a browser to provide natively. If it's not available in the browser, you being a developer, use your logics and implement the solution.

Some backstory...

I have been giving multiple interviews in past two months, and I have encountered multiple instances where I don't even know what Interviewer is asking about (it happens, it's okay!). Based on my experiences, I have decided to share the stuff that I faced and provide the detailed solution for them as per my research.

I'll be using Logic's albums as examples throughout my entire post just to show extra love for Hip Hop Music and easiness.

.forEach()

.forEach() function comes quite handy when we just need to iterate an array.

This function is quite useful because we don't need to implement for loop from scratch, hence saving our time and a lot of crap on the developer screen.

But what if we wanna implement our own polyfill for .forEach()?

We have an array of Logic's albums and want to iterate through this array and print out the album one by one.

var logicAlbums = [
  'Bobby Tarantino',
  'The Incredible True Story',
  'Supermarket',
  'Under Pressure',
]

First, let's just check how it works natively as provided by JavaScript.

logicAlbums.forEach(function(word) {
  console.log(word)
  // Bobby Tarantino,
  // The Incredible True Story,
  // Supermarket,
  // Under Pressure;
})

Since, it's an array, it makes sense to add a prototype to Array.

Array.prototype.eachAlbum = function(callback) {
  // callback here is the callback function
  // which actual .forEach() function accepts
  for (var i = 0; i < this.length; i++) {
    callback(this[i], i, this) // currentValue, index, array
  }
}

Let's try use our own polyfill

logicAlbums.eachAlbum(function(word) {
  console.log(word)
  // Bobby Tarantino,
  // The Incredible True Story,
  // Supermarket,
  // Under Pressure;
})

.map()

.map() is very much similar to .forEach() method, except for the fact, that instead of returning items out of the array, it return the array itself.

But what sense does it make if it returns the array itself?

.map() is used to iterate over the array, and do some manipulation in it with the items and then after doing that so, returns the manipulated array.

In Action

Let's use the collection of Logic's Albums again

var logicAlbums = [
  'Bobby Tarantino',
  'The Incredible True Story',
  'Supermarket',
  'Under Pressure',
]

Mapping these albums now using .map()

const mapThoseAlbums = logicAlbums.map(function(album) {
  return album
})

console.log(mapThoseAlbums)

// [
//   'Bobby Tarantino',
//   'The Incredible True Story',
//   'Supermarket',
//   'Under Pressure'
// ];

As we can see that, mapThoseAlbums returns an array.

So we are clear that we have to return an array in our own polyfill function. So let's create it then.

Array.prototype.ourMap = function(callback) {
  var arr = [] // since, we need to return an array
  for (var i = 0; i < this.length; i++) {
    arr.push(callback(this[i], i, this)) // pushing currentValue, index, array
  }
  return arr // finally returning the array
}

In Action

const mapThoseAlbums = logicAlbums.ourMap(function(album) {
  return album
})

console.log(mapThoseAlbums)
// [
// 'Bobby Tarantino',
// 'The Incredible True Story',
// 'Supermarket',
// 'Under Pressure'
// ];

.filter()

.filter() is very much similar to map() function except for the fact, it is used based on the context, where we decide what kind of items do we want in the resulting array.

Let's filter out Logic's greatest albums according to ratings

var logicAlbums = [
  {
    name: 'Bobby Tarantino',
    rating: 5,
  },
  { name: 'The Incredible True Story', rating: 4.5 },
  {
    name: 'Supermarket',
    rating: 4.9,
  },
  { name: 'Under Pressure', rating: 5 },
]

logicAlbums.filter(album => {
  return album.rating > 4.9
})
console.log(logicAlbums)

// [
//   { name: 'Bobby Tarantino', rating: 5 },
//   { name: 'Under Pressure', rating: 5 }
// ];

Now let's create our own polyfill for filter.

Array.prototype.filterAlbums = function(callback, context) {
  arr = []
  for (var i = 0; i < this.length; i++) {
    if (callback.call(context, this[i], i, this)) {
      arr.push(this[i])
    }
  }
  return arr
}
logicAlbums.filterAlbums(function(album) {
  return album.rating > 4.9 // providing the context here
})
console.log(logicAlbums)

// [
//   { name: 'Bobby Tarantino', rating: 5 },
//   { name: 'The Incredible True Story', rating: 4.5 },
//   { name: 'Supermarket', rating: 4.9 },
//   { name: 'Under Pressure', rating: 5 }
// ];

Over here, only albums with rating more than 4.9 will be returned which are Bobby Tarantino and Under Pressure (By the way, these are my favourites, that's why I rated them 5).

Under Pressure (2014)

Bobby Tarantino (2016)

.reduce()

reduce() function is used to reduce the array to a single value. We'll again take the example of Logic's best work yet and combine all of them in a single line using .reduce() function.

.reduce() accepts a callback function (accumulator, currentValue, index and array) and initial value

var logicAlbums = [
  'Bobby Tarantino',
  'The Incredible True Story',
  'Supermarket',
  'Under Pressure',
]
var withReduce = logicAlbums.reduce(function(a, b) {
  return a + ' , ' + b
}, 'Young Sinatra') // Here we are initialising the array with value as 'Young Sinatra'

console.log(withReduce)
// Young Sinatra , Bobby Tarantino , The Incredible True Story , Supermarket , Under Pressure

Let's create our own polyfill which is very easy.

Array.prototype.reduceAlbums = function(callback, initialValue) {
  var accumulator = initialValue === undefined ? undefined : initialValue

  for (var i = 0; i < this.length; i++) {
    if (accumulator !== undefined) {
      accumulator = callback.call(undefined, accumulator, this[i], i, this)
    } else {
      accumulator = this[i]
    }
  }
  return accumulator
} // our polyfill for reduce

var logicAlbums = [
  'Bobby Tarantino',
  'The Incredible True Story',
  'Supermarket',
  'Under Pressure',
]

var combineAlbums = logicAlbums.reduceAlbums(function(a, b) {
  return a + ' , ' + b
}, 'Young Sinatra') // Initial Value is Young Sinatra

console.log(combineAlbums)
// Young Sinatra , Bobby Tarantino , The Incredible True Story , Supermarket , Under Pressure

This article is really special for me since I am a huge fan of Logic. I tried to portray thw whole post with Logic's best work yet just to give a personal touch. If you are a Hip Hop head like me, don't forget to check his work on Internet.

Here's a tribute to his turning point of life that is, his album Young Sinatra.


Created, Broken and Enhanced with by @reeversedev