Skip to content

Instantly share code, notes, and snippets.

@paulcollett
Last active February 3, 2020 23:07
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 paulcollett/5b5ecebb6c06120cae632e7c69232032 to your computer and use it in GitHub Desktop.
Save paulcollett/5b5ecebb6c06120cae632e7c69232032 to your computer and use it in GitHub Desktop.
Quick JS template literal support
// Allows using a function as a template literal
// normal: myFunc('hello')
// template literal: myFunc`hello`
const myFunc = (...args) => {
// 1. get first and remaining arguments. Remaining args can be interpolated values
// 2. concat to force array. This allow us support normal myFunc('hello') usage
// 3. reduce to combine both template parts and interpolated values. This allows: myFunc`im at ${window.location}!!`
const [ templateRaw, ...templateArgs ] = args;
const template = [].concat(templateRaw).reduce((acc, templatePart, i) => acc += String(templatePart) + String(templateArgs[i] === undefined ? '' : templateArgs[i]), '')
return template
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment