Last active
July 25, 2018 18:09
-
-
Save iansan5653/4b6254c86614f65a1c9f5921dddacb6b to your computer and use it in GitHub Desktop.
Template literal tag function generator
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
/** | |
* @file generateTemplateLiteralTag gist. | |
* @author Ian Sanders <[email protected]> | |
* @license | |
* Public Domain - Attribution is nice but not at all required. Feel free to do | |
* anything with this code. | |
*/ | |
/** | |
* Generate a template literal tag that simply applies the given function on | |
* each placeholder value in the given template, using the placeholder value as | |
* the first argument and any other given arguments after that. | |
* @param {function(*, ...*): string} functionToApply The function that would | |
* be applied to the template placeholders. Should take a placeholder as the first | |
* argument and any number of arguments after that, and should always return | |
* a string or value that can be easily and predictably converted to a string. | |
* @param {...*} [extraArgs] Optional extra ordered arguments to pass to `functionToApply`. | |
* @returns {function(string[], ...*): string} A function that can be used | |
* as a tag for a string template literal. | |
* @example <caption>URL Parameter Escaper</caption> | |
* let urlEscape = generateTemplateLiteralTag(encodeURIComponent); | |
* let queryString = "This=will &=be ?=safely escaped!"; | |
* console.log(urlEscape`http://example.com?q=${queryString}&p=1`); | |
* // http://example.com?q=This%3Dwill%20%26%3Dbe%20%3F%3Dsafely%20escaped!&p=1 | |
* @example <caption>Lowercaser</caption> | |
* function lcString(string) { return string.toLowerCase(); } | |
* let lcPlaceholders = generateTemplateLiteralTag(lcString); | |
* let strings = ["StRiNg A", "STRING B", "String C"]; | |
* console.log(lcPlaceholders`In lowercase, your strings are ${strings.join(", ")}.`); | |
* // In lowercase, your strings are string a, string b, string c. | |
*/ | |
function generateTemplateLiteralTag(functionToApply, ...extraArgs) { | |
return function(strings, ...placeholders) { | |
return strings.reduce((result, string, i) => { | |
return (result + functionToApply(placeholders[i - 1], ...extraArgs) + string); | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment