Last active
November 13, 2017 14:12
-
-
Save aderaaij/55ee9cbf7e6f71f109c619640aae5d5f to your computer and use it in GitHub Desktop.
An example of 'tagging' an ES6 template string with a function. The function takes in the string as an argument and returns strings broken up by values as an array and the values as the rest of the arguments.
This file contains hidden or 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
const dict = { | |
HTML: 'Hyper Text Markup Language', | |
CSS: 'Cascading Style Sheets', | |
JS: 'JavaScript' | |
}; | |
/* Create the function we tag onto the template string. Tagging it to a template | |
string automatically returns the strings seperated by values as an array (strings) | |
and gives the values as the rest of the argument. */ | |
function addAbrriviations(strings, ...values) { | |
/* We use the es6 rest operator to get the rest of all the values */ | |
const abbreviated = values.map(value => { | |
if(dict[value]) { | |
return `<abbr title='${dict[value]}'>${value}</abbr>`; | |
} | |
return value; | |
}); | |
// Using array.reduce which takes in a function and an optional initial value | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce | |
return strings.reduce((sentence, string, i) => { | |
return `${sentence}${string}${abbreviated[i] || ''}` | |
}, ''); | |
} | |
const first = 'Arden'; | |
const last = 'de Raaij'; | |
const sentence = addAbrriviations`Hello, my name is ${first} ${last} and I love to code ${'HTML'}, ${'CSS'} and ${'JS'} `; | |
const p = document.createElement('p'); | |
p.innerHTML = sentence; | |
document.body.appendChild(p); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment