DEV Community

Lalit Yadav
Lalit Yadav

Posted on

4 1

JS Array method polyfills

Array.prototype.map()

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

  Array.prototype.myMap = function(callback) {
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }

    const obj = Object(this);
    let newArr = new Array(this.length);
    let i = 0;

    while (i < obj.length) {
      if (i in obj) {
        newArr[i] = callback.call(this, obj[i], i, obj);
      }
      i++;
    }

    return newArr;
  }
Enter fullscreen mode Exit fullscreen mode

Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

  Array.prototype.myFilter = function(callback) {
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }

    const obj = Object(this);
    let newArr = new Array(obj.length);
    let i = 0, actualLen = 0;

    while (i < obj.length) {
      if (i in obj) {
        if (callback.call(this, obj[i], i, obj)) {
          newArr[actualLen++] = obj[i];
        }
      }
      i++;
    }

    newArr.length = actualLen;

    return newArr;
  }
Enter fullscreen mode Exit fullscreen mode

Array.prototype.reduce()

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

  Array.prototype.myReduce = function(...args) {
    if (typeof args[0] !== 'function') {
      throw new TypeError(args[0] + ' is not a function');
    }

    const obj = Object(this);
    let i = 0;
    let result;

    if (args.length > 1) {
      result = args[1];
    } else {
      result = obj[i++];
    }

    while (i < obj.length) {
      if (i in obj) {
        result = args[0].call(this, result, obj[i], i, this);
      }
      i++;
    }

    return result;
  }
Enter fullscreen mode Exit fullscreen mode

The above polyfills are only meant for implementation purpose, the one provided on MDN are definitely better and one should not use their own polyfills over the API's methods. Thanks for reading :)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay