Behind Wikipedia Website - An Optimization

2 min read  •  11 Dec 2021
Views:

Wikipedia is surely one of the best things on the Internet, I use it to read about different things on a daily basis. I have immense respect for it, and being an engineer I thought to check how things were working behind there.


While I was looking there, I found out something (issue), which according to me can be optimized.


If you have used Wikipedia, you would know that on wiki' pages you can hover on different words and you will get a nice little preview card about them. Here's how it looks:


wiki-preview


So, what is happening here is whenever you hover on a word, there is an API call, which gives the information about that word as response and that information is shown in this card.


the issue


The issue here is - if we hover on a word again and again, it makes that API call everytime, which isn't a good thing to do. Here's how the API calls are made on hovering same words on a wiki' page:


issue


the solution


To reduce the number of API calls, we can maintain a mapping of words where we can store the data of API calls which are already being made.


const DATA_MAP = {};

async function onHoverWord(e) {
  const word = e.target.innerText;
  const data = await fetchInfo(word);
  createCard(data, e.target.parentElement);
}

function fetchInfo(word) {
  return new Promise((resolve, reject) => {
    if (DATA_MAP[word] !== undefined) {
      resolve(DATA_MAP[word]);
    } else {
      fetch(`https://en.wikipedia.org/api/rest_v1/page/summary/${word}`)
        .then((res) => res.json())
        .then((data) => {
          DATA_MAP[word] = data;
          resolve(data);
        })
        .catch(reject);
    }
  });
}

Here is how the solution looks:


solution


In the above solution, you can see that for the first time API call is made for each word but after first attempt no API call is being made.


The aim of above example is to provide solution for the multiple API calls issue and optimize that. The UI is just to help in demonstrating that.

You can find the references below: