DEV Community

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

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