-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathformat-text.js
49 lines (41 loc) · 1.06 KB
/
format-text.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
/**
* Format the text according to the template.
*
* @param {String} text Template that needs to be formatted.
* @param {Arguments..} .. The arguments that need to be applied.
* @returns {String} The replaced text.
*/
function format(text) {
var context;
if (typeof arguments[1] == 'object' && arguments[1]) {
context = arguments[1];
} else {
context = Array.prototype.slice.call(arguments, 1);
}
return String(text).replace(/\{?\{([^{}]+)}}?/g, replace(context));
};
/**
* Replaces the placeholders with the actual data.
*
* @param {object} context data for the template
* @returns {String} The new template data
* @private
*/
function replace(context){
return function replacer(tag, name) {
if (tag.substring(0, 2) == '{{' && tag.substring(tag.length - 2) == '}}') {
return '{' + name + '}';
}
if (!context.hasOwnProperty(name)) {
return tag;
}
if (typeof context[name] == 'function') {
return context[name]();
}
return context[name];
}
}
//
// Expose the actual module.
//
module.exports = format;