Last active
February 24, 2020 00:45
-
-
Save brenofreire/be1746848ac9f1df048eb07ccc5a6f48 to your computer and use it in GitHub Desktop.
Monta a frase de curtidas como no facebook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function likes(names) { | |
const 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', | |
]; | |
// Isso aqui é genial, porque se tiver muito nome ele não explode o template | |
const max = Math.min(names.length, templates.length - 1); | |
// A genialidade aqui tá no método de replace. | |
// Pega ou {name} ou {n} e substitui pelo nome da primeira pessoa do array (names.shift()) | |
// Ou insere o tamanho do resto do array porque foi tria por causa names.shift() :oooooooo | |
return templates[max].replace(/{name}|{n}/g, key => { | |
return key === '{name}' ? names.shift() : names.length; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment