JS Polyfills - Part 2 (forEach, keys, Values, Entries)

JS Polyfills - Part 2 (forEach, keys, Values, Entries)

·

2 min read

4. forEach()

  • Function: forEach(callback, thisArg)

  • Usage: arr.forEach((ele, index, arr)=>{...}, this)

  • Description: callback function will execute on every element. But not for uninitialized elements for sparse arrays.

  • Polyfill: forEach

//function returns undefined
Function.prototype.customForEach = function (callback) {
  //this should point to array
  if(Array.isArray(this)) {
    for (let i = 0; i < this.length; i++) {
      //check if each element exists
      if(typeof this[i] !== 'undefined') {
        //callback will take element, index and array as parameters
        callback(this[i], i, this);
      }
    }
  }
};

5. Keys()

  • Function: keys(obj)

  • Usage: Obj.keys(anyobj)

  • Description: returns array iterator

  • Polyfill:Keys

//function returns Array Iterator
Array.prototype.customKeys = function () {
  let keys = [];
    for (let i = 0; i < this.length; i++) {
      keys.push(i);
    }
    // A generator function which returns a generator object( basically follows iterator protocol)
    // Why we use here? because the keys return array iterator
    // A yield will pause and resume the function (Basically will return the keys one by one until done becomes true)
    function* iterator() {
      yield* keys;
    }

    return iterator();
};

6. Values()

  • Function: values(obj)

  • Usage: Obj.values(anyobj)

  • Description: returns array iterator

  • Polyfill:Values

//function returns Array Iterator
Array.prototype.customValues = function () {
  let values = [];
    for (let i = 0; i < this.length; i++) {
      values.push(this[i]);
    }
    // A generator function which returns a generator object( basically follows iterator protocol)
    // Why we use here? because the values return array iterator
    // A yield will pause and resume the function (Basically will return the values one by one until done becomes true)
    function* iterator() {
      yield* values;
    }

    return iterator();
};

7. Entries()

  • Function: entries(obj)

  • Usage: Obj.entries(anyobj)

  • Description: returns array iterator

  • Polyfill:Entries

//function returns Array Iterator
Array.prototype.customEntries = function () {
  let entries = [];
    for (let i = 0; i < this.length; i++) {
      entries.push(i, this[i]);
    }
    // A generator function which returns a generator object( basically follows iterator protocol)
    // Why we use here? because the entries return array iterator
    // A yield will pause and resume the function (Basically will return the entries one by one until done becomes true)
    function* iterator() {
      yield* entries;
    }

    return iterator();
};

Stay Tuned for Part 3 Keep Learning!

Find more polyfills @ Github: JS Polyfills