Map, Reduce and filter implementation in plain javascript
Lots of time , interview candidates are asked for implementation of map, reduce etc assuming they are not natively available. How about writing our own map, reduce and filter using callbacks. I hope this article will help few in understanding of callback pattern and higher order function in javascript. So Let’s start.
Below is the simple implementation of .map, .reduce and .filter function. Notice how we are making use of the callbacks that we are sending as an arguments. How we have the access of this(context) and how callback is called again inside the for loop. Notice one more thing that we are defining our definitions on Array.prototype. So that it will be available throughout the application.
General layout of these custom function will be like this
.map(callback)
.filter(callback)
.reduce(callback)
For reduce function, API is little different than others as it takes initialValue also as the second argument. we are using the same concept of looping through array, but also updating accumulator at every step. accumulator is available in the scope through scope chain. see line 7 in the snippet where we are updating accumulator value.
Over to you guys. Let me know whether you liked the article by hitting applause or comments. If you find any problems with the article please let me know. Note: The implementation of reduce, filter, map is not complete in this article in any sense 😄. This article just gave us a idea how these kind of util functions be written. Thanks everyone !!