Skip to content

Instantly share code, notes, and snippets.

@thetutlage
Created January 18, 2017 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thetutlage/cbbf3587ffa3b49792cc99b3ec2ca883 to your computer and use it in GitHub Desktop.
Save thetutlage/cbbf3587ffa3b49792cc99b3ec2ca883 to your computer and use it in GitHub Desktop.
Function to be used with tagged ES2015 template literals
function toSentence (strings, ...values) {
const nouns = values[0] || ''
const noun = values[1] || ''
const verb = values[2] instanceof Array === true ? (nouns.length ? values[2][1] : values[2][0]) : ''
const mappedString = strings.map((char, index) => {
if (index === 0 && !nouns) {
return `${char}${noun}`
} else if (index === 1 && !nouns) {
return ''
} else if (index === 2 && verb) {
return `${char}${verb}`
}
return `${char}${values[index] || ''}`
})
return mappedString.join('')
}
// EXAMPLE 2
const users = ['john', 'kirby', 'leo', 'tina']
const lastUser = users.pop()
console.log(toSentence `${users.join(', ')} and ${lastUser} ${['is', 'are']} online today`)
// EXAMPLE 2
const users = ['john']
const lastUser = users.pop()
console.log(toSentence `${users.join(', ')} and ${lastUser} ${['is', 'are']} online today`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment