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 :)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more