Skip to content

Instantly share code, notes, and snippets.

@secretgspot
Last active September 26, 2019 05:42
Show Gist options
  • Save secretgspot/e83dfbe6c691fcf8b2b375d1f5710b83 to your computer and use it in GitHub Desktop.
Save secretgspot/e83dfbe6c691fcf8b2b375d1f5710b83 to your computer and use it in GitHub Desktop.
let names = ['billy', 'jill', 'peter', 'john', 'richard'];
function likes(names) {
return {
0: 'no one likes this',
1: `${names[0]} likes this`,
2: `${names[0]} and ${names[1]} like this`,
3: `${names[0]}, ${names[1]} and ${names[2]} like this`,
4: `${names[0]}, ${names[1]} and ${names.length - 2} others like this`,
}[Math.min(4, names.length)]
}
likes(names);
////
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;
});
}
////
function likes(names) {
names = names || [];
switch(names.length){
case 0: return 'no one likes this'; break;
case 1: return names[0] + ' likes this'; break;
case 2: return names[0] + ' and ' + names[1] + ' like this'; break;
case 3: return names[0] + ', ' + names[1] + ' and ' + names[2] + ' like this'; break;
default: return names[0] + ', ' + names[1] + ' and ' + (names.length - 2) + ' others like this';
}
}
////
function likes(names) {
names.length === 0 && (names = ["no one"]);
let [a, b, c, ...others] = names;
switch (names.length) {
case 1: return `${a} likes this`;
case 2: return `${a} and ${b} like this`;
case 3: return `${a}, ${b} and ${c} like this`;
default: return `${a}, ${b} and ${others.length + 1} others like this`;
}
}
////
function likes (names) {
var format = {
0: "no one likes this",
1: "{0} likes this",
2: "{0} and {1} like this",
3: "{0}, {1} and {2} like this"
}[names.length] || "{0}, {1} and {n} others like this";
return format.replace(/{([\dn])}/g, function (_, n) {
return n == 'n' ? names.splice(2).length : names[parseInt(n, 10)];
});
}
////
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;
});
}
////
function likes(names) {
if(names.length === 0) return "no one likes this";
if(names.length === 1) return names[0] + " likes this";
if(names.length === 2) return names[0] + " and " + names[1] + " like this";
if(names.length === 3) return names[0] + ", " + names[1] + " and " + names[2] + " like this";
return names[0] + ", " + names[1] + " and " + (names.length - 2) + " others like this";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment