DEV Community

Lalit Yadav
Lalit Yadav

Posted on

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

Top comments (0)