DEV Community

Cover image for JavaScript Challenge 4: Who Likes It - [ES2021]
AlbertoM
AlbertoM

Posted on • Originally published at inspiredwebdev.com

JavaScript Challenge 4: Who Likes It - [ES2021]

This article was originally posted on my blog. Head over to inspiredwebdev.com for more articles and tutorials. Check out my JavaScript course on Educative to learn everything from ES6 to ES2020.

 

In this article we will solve together the Who Likes It challenge from CodeWars, you can find it at this link. The difficulty of this challenge is easy.

Let's read the task together:

You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.

Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:

likes [] -- must be "no one likes this"
likes ["Peter"] -- must be "Peter likes this"
likes ["Jacob", "Alex"] -- must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] -- must be "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] -- must be "Alex, Jacob and 2 others like this"

For 4 or more names, the number in and 2 others simply increases.

This challenge is a bit easier than the previous one we looked at and it shouldn't take us much to solve.

First, we'll try to solve it the conventional way, then I'll show you how we can approach it with one of the new features of ES2021.

Complete the challenge using a Switch statement

For this challenge we will use a switch statement an for each case we will return the requested string.

Let's start like this:

function likes(names) {
  names = names || [];
  switch(names.length){
    case 0: return 'no one likes this'; break;
  }
}

We initialized our simple function and in the first line we ensure that names exist, otherwise, we transform it into an empty Array.

We then start our switch statement using the length of the names Array as our cases.

The first one is very straightforward, for the second one onwards we will make use of string interpolation.

function likes(names) {
  names = names || [];
  switch(names.length){
    case 0: return 'no one likes this';
    case 1: return `${names[0]} likes this`;
    case 2: return `${names[0]} and ${names[1]} like this`;
    case 3: return `${names[0]}, ${names[1]} and ${names[2]} like this`;
    default: return `${names[0]}, ${names[1]} and ${(names.length - 2)} others like this`;
  }
}

If you don't know what ${} means, you can read more about string interpolation here

Since the challenge didn't pose any surprise, we could easily access the Array values at index 0 and 1 to display their names for all cases, using names.length -2 to display how many are left for our default case which will be used for any instance where we have 4 or more names.

Try to solve it with ES2021

ES2021 will bring many new additions to JavaScript one of which we will try to use for this challenge.

If you wanna learn more about everything coming to ES2021, please check out my article at this link.

We will try using Intl.ListFormat which is a constructor that enables language-sensitive list formatting.

Basically what it can do is create a formatted list from our initial Array based on a specific language, using either conjunctions or disjunctions.

const names = ["Max", "John", "Mark"];

const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });

console.log(formatter.format(names));
// Max, John, and Mark

Very cool right? Let's try to apply for our function:

function likes(names) {
  names = names || [];
  switch(names.length){
    case 0: 
        return 'no one likes this';
    case 1: 
        return 
            `${new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }).format(names)} likes this`; 
    case 2:
    case 3:
        return 
            `${new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }).format(names)} like this`; 
    default: 
        return `${names[0]}, ${names[1]} and ${(names.length - 2)} others like this`;
  }
}

As you can see, using Intl.ListFormat we combine case 1 to 3 into one, I had to split case 1 to use likes and like correctly but other than that the function is the same.

To see more examples, head over here.

I hope you found this useful, despite the challenge itself being very easy I wanted to show you something that many of you probably don't know yet.

There are many other ways of solving this problem, let me know yours in the comment.

If you liked this type of content, please let me know in the comments and I'll create more of these.


If you want to learn everything about JavaScript from ES6 all the way to ES2020, please check out my book available to read for free on Github. A course is also on Educative

Alt Text

 

Top comments (2)

Collapse
 
yoursunny profile image
Junxiao Shi

Won't work on iOS - the new IE.
caniuse.com/mdn-javascript_builtin...

Collapse
 
albertomontalesi profile image
AlbertoM

Yeah, ES2021 is still not widely supported. Good to use for a challenge but not for production yet