utils.js
1.28 KB
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
// Utility functions
// Copy all attributes from source object to destination object.
// destination object is mutated.
function extend(destination, source) {
destination = destination || {};
source = source || {};
for (var attrName in source) {
if (source.hasOwnProperty(attrName)) {
destination[attrName] = source[attrName];
}
}
return destination;
}
// Renders templates with given variables. Variables must be surrounded with
// braces without any spaces, e.g. {variable}
// All instances of variable placeholders will be replaced with given content
// Example:
// render('Hello, {message}!', {message: 'world'})
function render(template, vars) {
var rendered = template;
for (var key in vars) {
if (vars.hasOwnProperty(key)) {
var val = vars[key];
var regExpString = '\\{' + key + '\\}';
var regExp = new RegExp(regExpString, 'g');
rendered = rendered.replace(regExp, val);
}
}
return rendered;
}
function isString(obj) {
return typeof obj === 'string' || obj instanceof String;
}
function isFunction(obj) {
return typeof obj === 'function';
}
module.exports = {
extend: extend,
render: render,
isString: isString,
isFunction: isFunction
};