1
\$\begingroup\$

I had to make a single-page application that fetches some figures via an endpoint, does some calculations, and displays them to an HTML page. Below is my implementation. I know there is a lot of room for improvement. Looking forward to any feedback.

const getNumberOfTitles = async (title: string) => {
  try {
    const data: Response = await fetch(
      `https://${host}/?manga=${title}`
    );
    const response = await data.json();
    return response.number_of;
  } catch (error) {
    console.error('Error: ', error);
  }
};

const getNumberOfMultipleTitles = async (
  titleNames: Array<string>
) => {
  return Promise.all(titleNames.map(getNumberOfTitles));
};

const returnMangaData = async () => {
  const shounen = ['Naruto', 'Bleach'];
  const all_titles = [
    'AOT',
    'Death Note',
    'Full Metal Panic',
    'Demon Slayer',
    ...shounen,
  ];

  const totalShounenTitles = (
    await getNumberOfMultipleTitles(shounen)
  ).reduce((a, b) => parseInt(a) + parseInt(b));

  const totalMangaTitles = (
    await getNumberOfMultipleTitles(all_titles)
  ).reduce((a, b) => parseInt(a) + parseInt(b));

  const percentage = Math.round((totalShounenTitles / totalMangaTitles) * 100);
  return [totalShounenTitles, percentage];
};

const setMangaData = async () => {
  const [totalShounenTitles, percentage] = await returnMangaData();
  const shounenNumber = document.querySelector('.manga-shounen');
  if (shounenNumber) {
    shounenNumber.innerHTML = String(totalShounenTitles);
  }
  const shounenPercentage = document.querySelector('.shounen-percentage');
  if (shounenPercentage) {
    shounenPercentage.innerHTML = `This is ${percentage}% of shounen titles`;
  }
};

setMangaData();
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.