Created
January 22, 2020 14:58
-
-
Save voxpelli/d0624ee1725c95b3927632553ed5454f to your computer and use it in GitHub Desktop.
A small little helper for creating a template tag where one can modify the static strings, the values and/or the final output in some way. Eg. trim some whitespaces?
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
/** | |
* @template T | |
* @param {T} value | |
* @returns {T} | |
*/ | |
const passthrough = value => value; | |
/** | |
* @param {object} [options] | |
* @param {(value: string) => string} [options.staticCallback] | |
* @param {(value: string|number) => string} [options.valueCallback] | |
* @param {(value: string) => string} [options.finalCallback] | |
* @returns {(strings: TemplateStringsArray, ...values: (string|number)[]) => string} | |
*/ | |
const templateTagWithModifier = (options = {}) => { | |
if (!options || typeof options !== 'object') throw new TypeError('Expected argument to be an object'); | |
const { staticCallback, valueCallback, finalCallback } = options; | |
if (staticCallback && typeof staticCallback !== 'function') throw new TypeError('Expected staticCallback to be a function'); | |
if (valueCallback && typeof valueCallback !== 'function') throw new TypeError('Expected valueCallback to be a function'); | |
if (finalCallback && typeof finalCallback !== 'function') throw new TypeError('Expected finalCallback to be a function'); | |
/** | |
* @param {TemplateStringsArray} strings | |
* @param {...string|number} values | |
* @returns {string} | |
*/ | |
const func = (strings, ...values) => (finalCallback || passthrough)( | |
strings.reduce( | |
(result, value, i) => | |
result + | |
(staticCallback ? staticCallback(value) : value) + | |
(valueCallback ? valueCallback(values[i] || '') : (values[i] || '')), | |
'' | |
) | |
); | |
return func; | |
}; | |
module.exports = templateTagWithModifier; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment