-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathindex.js
More file actions
71 lines (66 loc) · 2.19 KB
/
Copy pathindex.js
File metadata and controls
71 lines (66 loc) · 2.19 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
const check = (origin, cache, count) => {
if (process.env.NODE_ENV !== 'production') {
for (let key in origin) {
if (cache.indexOf(key) === -1) {
cache.push(key);
} else {
count[key] ? count[key]++ : count[key] = 1;
}
}
}
}
const log = (model, constitute, count) => {
if (process.env.NODE_ENV !== 'production') {
let logCount = 0;
for (let key in count) {
if (!logCount) {
console.warn(`Please note that some of the attributes are inherited in the ${model.namespace} / ${constitute}:`);
}
logCount++;
console.warn(` -> ${key} be overwritten ${count[key]} time(s).`);
}
}
}
// 实现深拷贝的Object.assign
const deepObjectAssign = (target, source) => {
try {
if (source) {
// 对source进行判空,否则JSON.parse操作会报错: Unexpected token u in JSON at position 0
Object.assign(target, JSON.parse(JSON.stringify(source)))
}
} catch (e) {
console.log(e)
}
}
export default function modelExtend(...models) {
const base = { state: {}, subscriptions: {}, effects: {}, reducers: {}, };
const stateCache = [];
const stateCount = {};
const subscriptionsCache = [];
const subscriptionsCount = {};
const effectsCache = [];
const effectsCount = {};
const reducersCache = [];
const reducersCount = {};
const model = models.reduce((acc, extend) => {
acc.namespace = extend.namespace;
if (typeof extend.state === 'object' && !Array.isArray(extend.state)) {
check(extend.state, stateCache, stateCount)
deepObjectAssign(acc.state, extend.state);
} else if ('state' in extend) {
acc.state = extend.state;
}
check(extend.subscriptions, subscriptionsCache, subscriptionsCount)
Object.assign(acc.subscriptions, extend.subscriptions);
check(extend.effects, effectsCache, effectsCount)
Object.assign(acc.effects, extend.effects);
check(extend.reducers, reducersCache, reducersCount)
Object.assign(acc.reducers, extend.reducers);
return acc;
}, base);
log(model, 'state', stateCount)
log(model, 'subscriptions', subscriptionsCount)
log(model, 'effects', effectsCount)
log(model, 'reducers', reducersCount)
return model;
};