DEV Community

Discussion on: Day 1: Who likes it? - A coding challenge with solutions

Collapse
 
mattkenefick profile image
Matt Kenefick

Here's a solution that takes a few more things into account:

  • Singular vs Plural version of "like(s)"
  • How to concatenate the names "and" vs "&"
  • To use an oxford comma (always!)
  • Default name
  • Do not use conditional hell

function likes(...names) {
    const adjective = names.length > 1 ? 'like' : 'likes';
    const concatenator = 'and';

    // Empty list
    if (!names.length) names = ['No one'];

    const lastPerson = names.pop();
    const oxfordComma = names.length >= 2 ? ',' : '';
    const people = names.length 
        ? `${names.join(', ')}${oxfordComma} ${concatenator} ${lastPerson}`
        : lastPerson;
    const output = `${people} ${adjective} this`;

    console.log(output);
}


likes();
likes('Jack');
likes('Jack', 'Jill');
likes('Jack', 'Jill', 'Bill');
likes('John', 'Paul', 'George', 'Ringo');

// "No one likes this"
// "Jack likes this"
// "Jack and Jill like this"
// "Jack, Jill, and Bill like this"
// "John, Paul, George, and Ringo like this"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ubahthebuilder profile image
Kingsley Ubah

Awesome!

This is even shorter and better. Thanks for sharing.

Collapse
 
d3sox profile image
Nico

Nice solution. This does not say "and x others" though.

Collapse
 
mattkenefick profile image
Matt Kenefick

function likes(...names) {
    const adjective = names.length > 1 ? 'like' : 'likes';
    const concatenator = 'and';
    const maxNames = 3;
    const remainingCount = names.length - maxNames;
    const remainingCaption = remainingCount === 1 ? 'other' : 'others';

    // Empty list
    if (!names.length) {
        names = ['No one'];
    }

    const oxfordComma = names.length > 2 ? ',' : '';
    const lastPerson = remainingCount > 0 
        ? `${remainingCount} ${remainingCaption}` 
        : names.pop();
    const people = names.length === 0 
        ? lastPerson
        : `${names.slice(0, maxNames).join(', ')}${oxfordComma} ${concatenator} ${lastPerson}`;

    const output = `${people} ${adjective} this`;

    console.log(output);
}


likes();
likes('Jack');
likes('Jack', 'Jill');
likes('Jack', 'Jill', 'Bill');
likes('John', 'Paul', 'George', 'Ringo');
likes('John', 'Paul', 'George', 'Ringo', 'Archie');
likes('John', 'Paul', 'George', 'Ringo', 'Archie', 'Annie', 'Jeff', 'Abed');

// "No one likes this"
// "Jack likes this"
// "Jack and Jill like this"
// "Jack, Jill, and Bill like this"
// "John, Paul, George, and 1 other like this"
// "John, Paul, George, and 2 others like this"
// "John, Paul, George, and 5 others like this"
Enter fullscreen mode Exit fullscreen mode