Last active
February 3, 2020 23:07
-
-
Save paulcollett/5b5ecebb6c06120cae632e7c69232032 to your computer and use it in GitHub Desktop.
Quick JS template literal support
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
// 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