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
functionlikes(...names){constadjective=names.length>1?'like':'likes';constconcatenator='and';// Empty listif(!names.length)names=['No one'];constlastPerson=names.pop();constoxfordComma=names.length>=2?',':'';constpeople=names.length?`${names.join(', ')}${oxfordComma}${concatenator}${lastPerson}`:lastPerson;constoutput=`${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"
I'm a full-stack developer who loves to write about software programming and technology in general. Need a freelancer or want to collaborate? Send an email to my address below.
functionlikes(...names){constadjective=names.length>1?'like':'likes';constconcatenator='and';constmaxNames=3;constremainingCount=names.length-maxNames;constremainingCaption=remainingCount===1?'other':'others';// Empty listif(!names.length){names=['No one'];}constoxfordComma=names.length>2?',':'';constlastPerson=remainingCount>0?`${remainingCount}${remainingCaption}`:names.pop();constpeople=names.length===0?lastPerson:`${names.slice(0,maxNames).join(', ')}${oxfordComma}${concatenator}${lastPerson}`;constoutput=`${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"
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Here's a solution that takes a few more things into account:
Awesome!
This is even shorter and better. Thanks for sharing.
Nice solution. This does not say "and x others" though.