HomeTutorialsArticlesAbout MeContact

JS Challenge 4: Who Likes it?

By Alberto Montalesi
Published in Challenge
October 12, 2020
2 min read
Check out my Github for my free-to-read JavaScript Ebook that covers all the new features from ES6 to 2021. If you want find a great place for interactive tutorials, i recommend Educative where you can find my JavaScript course
This website contains affiliate links.

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.

test

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.


Thank you very much for reading, if you enjoyed this article, please share it with friends and colleagues and if there is a topic you would like me to cover, reach out to me on twitter at @montalesi. Follow me on DevTo or on Twitter for more.

complete guide to modern javascript alberto montalesi ebook bannerGet my ebook on Leanpub or get my course on Educative

Tags

challenge
Previous Article
JS Challenge 3: Remove Zeroes

Alberto Montalesi

Software Developer

buy me coffee
complete guide to modern javascript book cover

Complete Guide to Modern JavaScript

Get the Course

Category

Article
Challenge
Tutorial

Related Posts

JS Challenge 7: Multiples of 3 or 5
October 28, 2020
1 min
© 2021, All Rights Reserved.

Quick Links

TutorialsArticlesChallenges

Social Media