DEV Community

Cover image for Javascript Polyfill Array.map #3
chandra penugonda
chandra penugonda

Posted on • Edited on

Javascript Polyfill Array.map #3

This problem was asked by Amazon.

What is a polyfill ?

In web development, a polyfill is code that implements a feature on web browsers that do not natively support the feature

Please implement your own Array.prototype.map().

Example

[1,2,3].myMap(num => num * 2) // [2,4,6]
[1, 4, 9, 16].myMap(num => num * 2) // [2, 8, 18, 32]

Enter fullscreen mode Exit fullscreen mode

Note: Do not use native Array.prototype.map() in your code

Solution

if (!Array.prototype.customMap) {
  Array.prototype.customMap = function (cb, args) {
    const len = this.length;
    const result = new Array(len);
    if (typeof cb !== "function") {
      throw new TypeError(cb + " is not a function");
    }
    for (let i = 0; i < len; i++) {
      result[i] = cb.call(args, this[i], i, this);
    }
    return result;
  };
}
Enter fullscreen mode Exit fullscreen mode
  • This polyfill defines the .map() method on Array.prototype if it does not already exist natively. It implements the .map() functionality by:
  • Checking if .map() exists, and if not, defining it
  • Checking the this value is defined
  • Getting the length of the array
  • Checking if the callback is a function
  • Handling an optional thisArg
  • Creating a new array to store the results
  • Iterating through the array using a for loop
  • Calling the callback on each element and storing the result in the new array
  • Returning the new array

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay