Skip to content

Instantly share code, notes, and snippets.

@voxpelli
Created January 22, 2020 14:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voxpelli/d0624ee1725c95b3927632553ed5454f to your computer and use it in GitHub Desktop.
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?
/**
* @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