mix.js
2.59 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
var hasOwnProperty = Object.prototype.hasOwnProperty;
var shape = {
generic: true,
types: {},
properties: {},
parseContext: {},
scope: {},
atrule: ['parse'],
pseudo: ['parse'],
node: ['name', 'structure', 'parse', 'generate', 'walkContext']
};
function isObject(value) {
return value && value.constructor === Object;
}
function copy(value) {
if (isObject(value)) {
var res = {};
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
res[key] = value[key];
}
}
return res;
} else {
return value;
}
}
function extend(dest, src) {
for (var key in src) {
if (hasOwnProperty.call(src, key)) {
if (isObject(dest[key])) {
extend(dest[key], copy(src[key]));
} else {
dest[key] = copy(src[key]);
}
}
}
}
function mix(dest, src, shape) {
for (var key in shape) {
if (hasOwnProperty.call(shape, key) === false) {
continue;
}
if (shape[key] === true) {
if (key in src) {
if (hasOwnProperty.call(src, key)) {
dest[key] = copy(src[key]);
}
}
} else if (shape[key]) {
if (isObject(shape[key])) {
var res = {};
extend(res, dest[key]);
extend(res, src[key]);
dest[key] = res;
} else if (Array.isArray(shape[key])) {
var res = {};
var innerShape = shape[key].reduce(function(s, k) {
s[k] = true;
return s;
}, {});
for (var name in dest[key]) {
if (hasOwnProperty.call(dest[key], name)) {
res[name] = {};
if (dest[key] && dest[key][name]) {
mix(res[name], dest[key][name], innerShape);
}
}
}
for (var name in src[key]) {
if (hasOwnProperty.call(src[key], name)) {
if (!res[name]) {
res[name] = {};
}
if (src[key] && src[key][name]) {
mix(res[name], src[key][name], innerShape);
}
}
}
dest[key] = res;
}
}
}
return dest;
}
module.exports = function(dest, src) {
return mix(dest, src, shape);
};