📌  相关文章
📜  Day 5: Template Literals hackerrank 10 天的 javascript 解决方案 - Javascript (1)

📅  最后修改于: 2023-12-03 15:00:21.653000             🧑  作者: Mango

Day 5: Template Literals Hackerrank 10-Day Javascript Challenge Solution - Javascript

Welcome to Day 5 of the Hackerrank 10-Day Javascript Challenge! Today we will be discussing Template Literals.

Template Literals is a new feature introduced in ES6 that allows for easier string interpolation. It allows you to embed expressions and variables inside of a string using backticks (`).

Here's an example:

const name = "John";
console.log(`Hello ${name}!`);

The output will be:

Hello John!

As you can see, we used a template literal to embed the name variable inside of the string.

Now let's move on to today's challenge!

Challenge

Given two integers, a and b, write a function getDayName(a, b) that returns the day of the week corresponding to the date a/b/2020.

Here's the function signature:

function getDayName(a, b) {

}

You are allowed to use one of the following libraries: moment.js, date-fns, or day.js.

Solution

We can use the toLocaleDateString() function in conjunction with template literals to get the day of the week. Here's the solution using moment.js:

function getDayName(a, b) {
  const date = moment(`2020-${a}-${b}`).toDate();
  const dayOfWeek = new Intl.DateTimeFormat('en-US', { weekday: 'long' }).format(date);
  return dayOfWeek;
}

And here's the solution using date-fns:

function getDayName(a, b) {
  const date = new Date(`2020-${a}-${b}`);
  const dayOfWeek = format(date, 'dddd');
  return dayOfWeek;
}

And finally, here's the solution using day.js:

function getDayName(a, b) {
  const date = dayjs(`2020-${a}-${b}`);
  const dayOfWeek = date.format('dddd');
  return dayOfWeek;
}

As you can see, all of the solutions are very similar. We create a new Date or dayjs object using the given integers, and then use the appropriate library function to get the day of the week.

I hope this helps you understand Template Literals and how to use them to solve the Day 5 challenge in the Hackerrank 10-Day Javascript Challenge!