-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
71 lines (64 loc) · 2.26 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* TemplateString - Simple template strings
* Copyright (c) Abdulsamii Ajala (jalasem)
* https://github.com/jalasem/templateString/
*
* Released under the MIT license
* https://github.com/jalasem/templateString/blob/master/LICENSE
*/
/**
* Processes a template string by interpolating values based on a given configuration.
*
* @param {string} template - Template string to be processed.
* @param {object} values - Variables to be interpolated into the template.
* @param {object} config - Configurations for template interpolation with defaults.
* @returns {string} - The processed template string.
*/
const processTemplate = (template, values, config = settings()) => {
const { openingBracket, closingBracket, trim } = config;
const flattenedValues = flattenObj(values);
if (typeof flattenedValues !== 'object' || Array.isArray(flattenedValues)) {
return template;
}
return Object.entries(flattenedValues).reduce((acc, [key, value]) => {
const pattern = trim ? `${escapeRegExp(openingBracket)}\\s*${key}\\s*${escapeRegExp(closingBracket)}` : `${escapeRegExp(openingBracket)}${key}${escapeRegExp(closingBracket)}`;
const regex = new RegExp(pattern, "gm");
return acc.replace(regex, value);
}, template);
};
/**
* Escapes special characters in a string for use in a regular expression.
*
* @param {string} str - String to be escaped.
* @returns {string} - Escaped string.
*/
const escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
/**
* Flattens a nested object into a single-level object with dot-separated keys.
*
* @param {object} obj - Object to be flattened.
* @returns {object} - Flattened object.
*/
const flattenObj = (obj, base = '', result = {}) => {
Object.entries(obj).forEach(([key, value]) => {
const newKey = base ? `${base}.${key}` : key;
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
flattenObj(value, newKey, result);
} else {
result[newKey] = value;
}
});
return result;
};
/**
*
* @returns {object} default configurations or settings
*/
const settings = () => {
return {
openingbracket: '{',
closingbracket: '}',
trim: true // auto trim excess white spaces between key value and brackets
}
}
module.exports = processTemplate