The Power of JavaScript's Map Object

The Power of JavaScript's Map Object

Keep your codebase cleaner with Map

ยท

4 min read

Introduction

I was just given the assignment of using client-side solely to redirect some of our existing QR Code URLs to new ones. I utilized JavaScript's built-inMap object for this, which debuted in ES6 (2015). worked perfectly with better performance. Unlike JavaScript's default data structure, Objects, where thekey must be a string (or symbols), a Map maintains collections of unique and ordered key-value pairs where the keys can be any datatype ๐Ÿ‘๐Ÿ‘๐Ÿ‘

This lesson will teach us how to utilize Map effectively to address a certain issue.

Prerequisites

You should have a basic understanding of JavaScript ES6, Object data type and window object.

Problem Statement

Redirect existing QR Code URLs to new ones on client-side.

For example, if the existing URL is https://hashnode.com/{oldQRCode} then redirect it to a new QR Code https://hashnode.com/{newQRCode} The origin name https://hashnode.com/ is unchanged.

You are given N number of QR URLs with their redirections as below:

This proposed solution is not the best one as things could be done easily on the backend with better performance but it's something we should consider to understand how useful Map is.

Problem Solving

Looking at the problem statement you already learned that the origin name in the URL won't be changed. The only thing that need to be replaced is the QR Code part which comes after the last / of the URL. Maybe at this point, you are thinking of putting all the QR Codes in an array of strings, running for loop over that and then using an amateurish if-else if-else? ๐Ÿ™‰

Instead you can simplify your code with Map object! It really is that easy trust me!

Let's look at the process for doing that step by step: ๐Ÿ˜Ž

Creating Variables

First of all you need to create 3 different type of variables:

      let currentQRCode = '';
      let newQRCode = '';
      const currentUrl = window.location.href; // to get the current URL which is hashnode.com

Creating a New Map

Creating a new Map object is really simple. All you have to do is to initialize a variable called qrMap with new Map(). You can set all your QR Code items inside that as below:

.set() Method

.set() method is used to fill your empty Map object. It takes two parameters: a key for identification and the value of that specific item.

const qrCodeMap = new Map();
qrCodeMap.set(key, value);

Instead of setting each items, you can easily pass all the key-value items inside an array. Please note that it's basically [currentQRCode, newQRCode] structure:

  const qrCodeMap = new Map([
        ['xUzs456789aW', '9xsdfYteRpLzA'],
        ['uYlP09876TgD', '54hZxcvsfDgt'],
        ['8hDywr342516', 'lKjhft6790Cz'],
        ['dLp098yHgdRa', 'Plmng6dZqwrY'],
        ['pogYbnzqwe32', 'LkmnTyuDrZ12'],
        ...
      ]);

Getting Only the QR Code Part

currentQRCode = currentUrl?.split('/')?.pop(); // this will return xUzs456789aW

Mapping the QR Codes with .get() Method

Use the .get() method to get a value from the Map object. To get a value back, you need to know the key.

For example, to retrieve a value from the qrCodeMap Map object you need to append the .get() method with a known key like this:

newQRCode = qrCodeMap.get(currentQRCode);

Build New URL with New QR Code

if (newQRCode) {
  const newUrl = `${window.location.origin}/${newQRCode}`; // this will construct a new URL like https://hashnode.com/9xsdfYteRpLzA
  window.location.href = newUrl; // redirect current URLs to new ones
}

Full Code

const redirectQRCodes = () => {
    let currentQRCode = '';
    let newQRCode = '';
    const currentUrl = window.location.href; // to get the current URL which is hashnode.com

    const qrCodeMap = new Map([
      ['xUzs456789aW', '9xsdfYteRpLzA'],
      ['uYlP09876TgD', '54hZxcvsfDgt'],
      ['8hDywr342516', 'lKjhft6790Cz'],
      ['dLp098yHgdRa', 'Plmng6dZqwrY'],
      ['pogYbnzqwe32', 'LkmnTyuDrZ12'],
      // ... N number of QR codes
    ]);

    currentQRCode = currentUrl?.split('/')?.pop(); // this will return xUzs456789aW
    newQRCode = qrCodeMap.get(currentQRCode);

    if (newQRCode) {
      const newUrl = `${window.location.origin}/${newQRCode}`; // this will construct a new URL like https://hashnode.com/9xsdfYteRpLzA
      window.location.href = newUrl; // redirect current URLs to new ones
    }
}

// to invoke it
redirectQRCodes()

Now whenever this redirectQRCodes function gets invoked you will see all your existing URLs to be redirected to the new ones ๐Ÿš€ ๐Ÿš€

See how simple was that! โ˜๏ธ

References

MDN Web Docs on Map

ย