Created
January 18, 2017 08:18
-
-
Save thetutlage/cbbf3587ffa3b49792cc99b3ec2ca883 to your computer and use it in GitHub Desktop.
Function to be used with tagged ES2015 template literals
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 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