-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
58 lines (52 loc) · 1.45 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
/**
* render function is copy from https://segmentfault.com/a/1190000004428305
* @param {String} template
* @param {*} context
* @return {String}
*/
function render(template, context) {
const tokenReg = /\{([^{}]+)\}/g;
return template.replace(tokenReg, function(word, token) {
const variables = token.replace(/\s/g, '').split('.');
let currentObject = context;
let i; let length; let variable;
for (i = 0, length = variables.length; i < length; ++i) {
variable = variables[i];
currentObject = currentObject[variable];
if (currentObject === undefined || currentObject === null) return '';
}
return currentObject;
});
}
/**
* mapConvert
* @param {Object} source source Data
* @param {*} schema definition schema
* @return {*}
*/
function mapConvert(source, schema) {
let ret = {};
switch (Object.prototype.toString.call(schema)) {
case '[object Object]':
for (const key in schema) {
if (Object.prototype.hasOwnProperty.call(schema, key)) {
ret[key] = mapConvert(source, schema[key]);
}
}
break;
case '[object Array]':
ret = schema.map((itemSchema) => mapConvert(source, itemSchema));
break;
case '[object String]':
ret = render(schema, source);
break;
case '[object Function]':
ret = schema(source);
break;
default:
ret = schema;
}
return ret;
}
module.exports = mapConvert;
exports.mapConvert = mapConvert;