Polyfill (map, filter, reduce)

Polyfill (map, filter, reduce)

No alt text provided for this image


I'm thrilled to share with you some custom Polyfill implementations in JavaScript! 😄

1️⃣ Polyfill for map():

Array.prototype.myMap = function(cb) {
  let temp = [];
  for (let i = 0; i < this.length; i++) {
    temp.push(cb(this[i], i, this));
  }
  return temp;
}


const nums = [12, 32, 1, 3, 44, 3, 2];
const multiplyByThree = nums.myMap(num => num * 3);        

2️⃣ Polyfill for filter():

Array.prototype.myFilter = function(cb) {
  let temp = [];
  for (let i = 0; i < this.length; i++) {
    if (cb(this[i], i, this)) {
      temp.push(this[i]);
    }
  }
  return temp;
}


const nums = [12, 32, 1, 3, 44, 3, 2];
const numGreaterThanThree = nums.myFilter(num => num > 3);        

3️⃣ Polyfill for reduce():

Array.prototype.myReduce = function(cb, initialValue) {
  let accumulator = initialValue !== undefined ? initialValue : this[0];
  for (let i = initialValue !== undefined ? 0 : 1; i < this.length; i++) {
    accumulator = cb(accumulator, this[i], i, this);
  }
  return accumulator;
};


const nums = [1, 2, 3, 4, 5];
const sum = nums.myReduce((acc, curr) => {
  return acc + curr;
}, 0);        

These custom Polyfills will enhance your JavaScript skills and allow you to use map(), filter(), and reduce() methods in older environments where they might not be available by default.

Happy coding! 💻🚀 Let me know if you have any questions or thoughts in the comments below. Keep learning and keep coding! 💪😊

#javascript #coding #techcommunity #webdevelopment #programming

To view or add a comment, sign in

More articles by Lokesh jha

Insights from the community

Others also viewed

Explore topics