Passed
Push — master ( d53bd6...a69789 )
by Stéphan
02:25 queued 39s
created

src/mixin.js   A

Complexity

Total Complexity 7
Complexity/F 1

Size

Lines of Code 38
Function Count 7

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 7
eloc 19
dl 0
loc 38
rs 10
c 0
b 0
f 0
mnd 0
bc 0
fnc 7
bpm 0
cpm 1
noi 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A mixin.js ➔ copyProps 0 11 3
1
/**
2
 * @example
3
 * class FooClass extends mixin(TraitClass, OtherTraitClass) {
4
 *     // ...
5
 * }
6
 * @param MixTrait
7
 * @param traits
8
 */
9
export default function mixin(MixTrait, ...traits) {
10
    class Mix extends MixTrait {
11
        constructor(...args) {
12
            super(...args);
13
14
            // copy properties and symbols
15
            traits.forEach((Trait) => {
16
                const instance = new Trait(...args);
17
                copyProps(this, instance);
18
            });
19
        }
20
    }
21
22
    // copy static properties and symbols
23
    traits.forEach((Trait) => {
24
        copyProps(Mix.prototype, Trait.prototype);
25
        copyProps(Mix, Trait);
26
    });
27
28
    return Mix;
29
}
30
31
/**
32
 * Copy properties from source to target.
33
 * @param target
34
 * @param source
35
 */
36
function copyProps(target, source) {
37
    const properties = Object.getOwnPropertyNames(source);
38
39
    properties
40
        .concat(Object.getOwnPropertySymbols(source))
41
        .filter((key) => !key.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/))
42
        .forEach((key) => {
43
            const props = Object.getOwnPropertyDescriptor(source, key);
44
            Object.defineProperty(target, key, props);
45
        });
46
}
47