-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mixin.js
54 lines (44 loc) · 1.16 KB
/
Mixin.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
/**
* Creates a new prototype mixing all the given prototypes. Incase two or more
* prototypes contain the same propterty, the new prototype will return
* the propterty of the first prototype in the list which contains it.
*
* @param {...Object} prototypes
* @return {Proxy}
*/
export var Mixin = function(...prototypes){
return new Proxy(prototypes, MixinTrap);
};
/**
* Internal function to find a proptery in a list of prototypes.
*
* @param {Object[]} prototypes
* @param {string} key
* @return {Object}
*/
var findProperty = function(prototypes, key) {
for (var i = 0; i < prototypes.length; i++) {
var item = prototypes[i];
if (item[key]) {
return item;
}
}
return undefined;
};
/**
* Traps to create a mixin.
*/
var MixinTrap = {
'get' : function(prototypes, key) {
var object = findProperty(prototypes, key);
return (object ? object[key] : null);
},
'set' : function(prototypes, key, value) {
var object = findProperty(prototypes, key);
if (object) {
object[key] = value;
} else {
prototypes[0][key] = value;
}
}
};