fromModel.ts ➔ arrayToObjects   F
last analyzed

Complexity

Conditions 17

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
eloc 5
dl 0
loc 5
rs 1.8
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like fromModel.ts ➔ arrayToObjects often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import Field from "../../Store/Model/Field";
2
import Relation from "../../Store/Model/Relation";
3
import MorphTo from "../../Store/Model/Field/MorphTo";
4
5
export default function (model, fromRelation = false) {
6
    const json = {};
7
8
    for (let i = 0; i < model.originalFields.length; i++) {
9
        const field = model.originalFields[i];
10
        if (field instanceof Relation && fromRelation) {
11
            continue
12
        }
13
14
        if (field instanceof MorphTo && fromRelation) {
15
            continue;
16
        }
17
18
19
        if (Array.isArray(json[field.name])) {
20
            json[field.name] = arrayToObjects(json, field);
21
        } else if (field instanceof Relation) {
22
            json[field.name] = field?.value?.toObject?.(true) ?? null;
23
        } else {
24
            json[field.name] = field.value;
25
        }
26
    }
27
28
    return {...json};
29
}
30
31
function arrayToObjects(json: object, field: Field): Array<unknown> {
32
    return [...json[field.name].map((value) => {
33
        return (value?.toObject(true) ?? value)
34
    }) ?? []];
35
}