Refactor template.js

Added:
- Function `resolve()` to process any template tags (in a string) in objects and arrays.

Changed:
- Renamed function `template()` to `resolveValue()`.
- Replaced default export `resolveValue()` with new function `resolve()`.
This commit is contained in:
Chauncey McAskill
2022-03-22 16:08:29 -04:00
parent d49d3eabb2
commit 48bd911804
6 changed files with 63 additions and 25 deletions

View File

@@ -14,17 +14,53 @@ const templateData = flatten({
* If replacement pairs contain a mix of substrings, regular expressions,
* and functions, regular expressions are executed last.
*
* @param {string} input - The string being searched and replaced on.
* @param {object} data - An object in the form `{ 'from': 'to', … }`.
* @param {*} input - The value being searched and replaced on.
* If input is, or contains, a string, tags will be resolved.
* If input is, or contains, an object, it is mutated directly.
* If input is, or contains, an array, a shallow copy is returned.
* Otherwise, the value is left intact.
* @param {object} [data] - An object in the form `{ 'from': 'to', … }`.
* @return {*} Returns the transformed value.
*/
export default function resolve(input, data = templateData) {
switch (typeof input) {
case 'string': {
return resolveValue(input, data);
}
case 'object': {
if (input == null) {
break;
}
if (Array.isArray(input)) {
return input.map((value) => resolve(value, data));
} else {
for (const key in input) {
input[key] = resolve(input[key], data);
}
}
}
}
return input;
}
/**
* Replaces all template tags in a string from a map of keys and values.
*
* If replacement pairs contain a mix of substrings, regular expressions,
* and functions, regular expressions are executed last.
*
* @param {string} input - The string being searched and replaced on.
* @param {object} [data] - An object in the form `{ 'from': 'to', … }`.
* @return {string} Returns the translated string.
*/
export default function template(input, data) {
export function resolveValue(input, data = templateData) {
const tags = [];
if (data) {
if (data !== templateData) {
data = flatten(data);
} else {
data = templateData;
}
for (let tag in data) {
@@ -55,7 +91,7 @@ export default function template(input, data) {
return '';
});
};
}
/**
* Creates a new object with all nested object properties