DEV Community

Cover image for JS Polyfills - Part 3 (Map, Filter, Reduce)
Sriya
Sriya

Posted on • Updated on

JS Polyfills - Part 3 (Map, Filter, Reduce)


Github Code: JS Polyfills
8. Map()

  • Function: map(callback, thisArg)
  • Usage: arr/obj.map(function(element, index, array) { /* … */ }, thisArg)
  • Description: creates a new array populated with the results of callback function on every element in the calling array.
  • Polyfill & test cases: Map
//function returns Array, Map will have callbackfunction
Array.prototype.customMap = function (callbackFunction) {
  const arr = [];

  for (let i = 1; i <= this.length; i++) {
    arr.push(callbackFunction.call(this[i], i, this));
  }
  return arr;
};

Enter fullscreen mode Exit fullscreen mode

9. Filter()

  • Function: filter(callbackFn, thisArg)
  • Usage: arr.filter(function(element, index, array) { /* … */ }, thisArg)
  • Description: creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
  • Polyfill & test cases:Filter
//function returns Array, filter will have callbackfunction
Array.prototype.customFilter = function (callbackFunction) {
  const arr = [];

  for (let i = 0; i <= this.length; i++) {

    (callbackFunction(this[i], i, this)) ? arr.push(this[i])  : null;
  }
  return arr;
};
Enter fullscreen mode Exit fullscreen mode

10. Reduce()

  • Function: reduce(callbackFn, initialValue)
  • Usage: arr/obj.reduce(function(previousValue, currentValue, currentIndex, array) { /* … */ }, initialValue)
  • Description: executes a "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
  • Polyfill & test cases:Reduce
// expects callback function called reducer and initial value
//Parameters - (function(previousValue, currentValue, currentIndex, array) { /* … */ }, initialValue)
// reducer call back is executed on every element of the array and reduces it to a single value.
Array.prototype.customReduce = function (reducerCallback, initial) {
  //previous value also called as accumulator will be either provided initial value or undefined if no previous value exists
  let previousValue = initial || undefined;
  for (let i = 0; i < this.length; i++) {
    //if accumulator exists and is not undefined then reducer callback is called otherwise previous value is set as current value
    (previousValue) ? reducerCallback.call(previousValue, this[i], i, this) : (previousValue = this[i]);
  }
  return previousValue;
}
Enter fullscreen mode Exit fullscreen mode

Stay Tuned for Part 4 - Debouncer & Throttle
Keep Learning!

Top comments (0)