Passed
Push — main ( bf6dd7...eb8b76 )
by Andrii
02:10
created

bem.core.ts ➔ bem2arr   D

Complexity

Conditions 13

Size

Total Lines 49
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 41
dl 0
loc 49
c 0
b 0
f 0
rs 4.2
cc 13

How to fix   Complexity   

Complexity

Complex classes like bem.core.ts ➔ bem2arr 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 type { BemAbsraction } from "./bem.types"
2
3
let elementDelimiter = "__"
4
, modDelimiter = "--"
5
, blockModKey = "$"
6
7
export type BemOptions = {
8
  elementDelimiter: string
9
  modDelimiter: string
10
  blockModKey: string
11
}
12
13
export {
14
  bem2arr,
15
  setOptions,
16
  getOptions
17
}
18
19
function bem2arr(query: BemAbsraction) {
20
  const $return: string[] = []
21
22
  for (const block in query) {
23
    const blockQ = query[block]
24
    
25
    if (!blockQ) 
26
      continue
27
    if (typeof blockQ !== "object") {
28
      $return.push(block)
29
      if (typeof blockQ === "string")
30
        $return.push(`${block}--${blockQ}`)
31
      continue
32
    }
33
34
    for (const el in blockQ) {
35
      const elementQ = blockQ[el]
36
      , isBlockMod = el === blockModKey
37
      , element = isBlockMod ? block : `${block}${elementDelimiter}${el}`
38
      
39
      if (!elementQ) {
40
        isBlockMod && $return.push(element)
41
        continue
42
      }
43
      
44
      $return.push(element)
45
46
      if (typeof elementQ !== "object") {
47
        if (typeof elementQ === "string")
48
          $return.push(`${element}--${elementQ}`)
49
        continue
50
      }
51
52
      for (const mod in elementQ) {
53
        const modValue = elementQ[mod]
54
        if (!modValue)
55
          continue
56
57
        $return.push(`${element}${modDelimiter}${mod}${
58
          typeof modValue !== "string"
59
          ? ""
60
          : `${modDelimiter}${modValue}`
61
        }`)
62
      }
63
    }
64
  }
65
  
66
  return $return
67
}
68
69
function setOptions({
70
  elementDelimiter: elD = elementDelimiter,
71
  modDelimiter: modDel = modDelimiter,
72
  blockModKey: modKey = blockModKey
73
}: Partial<BemOptions>) {
74
  elementDelimiter = elD
75
  modDelimiter = modDel
76
  blockModKey = modKey
77
}
78
79
function getOptions() {
80
  return {
81
    elementDelimiter,
82
    modDelimiter,
83
    blockModKey
84
  }
85
}