Hi recently while training in code wars i stumbled upon this solution. The case that needs to solved is as follows: 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" ////////////////////////////////////////////////////////////////////////////////////////////
In return I found a code written like so:
var names=["Erica", "Steven","Dono", "Erick"];
function likes (names) {
var templates = [
'no one likes this',
'{name} likes this',
'{name} and {name} like this',
'{name}, {name} and {name} like this',
'{name}, {name} and {n} others like this'
];
var idx = Math.min(names.length, 4);
return templates[idx].replace(/{name}|{n}/g, function (val) {//
return val === "{name}" ? names.shift() : names.length;//
});
}
var runlikes= likes(names);
console.log(runlikes);
For the solution I found a very good one described like shown there. I do get the code until it gets to the.replace function. I dont get how the code is able to get the name Erica,Steven, and Dono and the amount of numbers left to replace n with.How could n get it's number after the other two names has been used? How is ":" able to be used there, isn't it only for objects and how does it work ? What is the use of return val === "{name} " and how is this line of code knows when to switch to {n}. I know I've been asking very noob questions and I'm sorry for that I'm still in Highschool and just doing this as a prep for uni. Thank you for yout time