-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
33 lines (28 loc) · 1.11 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
export default function makeControllable(props, state, propsMapping) {
if (typeof props !== 'object' || (typeof propsMapping !== 'object' && typeof propsMapping !== 'string')) {
return null;
}
if (typeof propsMapping === 'string') {
propsMapping = {
[propsMapping]: propsMapping
};
}
let newState = null;
const propsToCheck = Object.keys(propsMapping);
for (let i = 0, l = propsToCheck.length; i < l; i++) {
const currentState = state || {};
const propKey = propsToCheck[i];
const stateKey = propsMapping[propKey] || propKey;
const prop = props[propKey];
const prevProp = currentState['__makeControllable'] ? currentState['__makeControllable'][propKey] : undefined;
if (prop !== prevProp) {
newState = newState || {};
newState['__makeControllable'] = newState['__makeControllable'] || {};
newState['__makeControllable'][propKey] = prop;
if (prop !== currentState[stateKey]) {
newState[stateKey] = prop;
}
}
}
return newState;
}