Completed
Push — master ( 651c35...c2f34b )
by greg
03:07
created

dom.js ➔ getClosest   D

Complexity

Conditions 10
Paths 24

Size

Total Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
nc 24
nop 2
dl 0
loc 38
cc 10
rs 4.8196

How to fix   Complexity   

Complexity

Complex classes like dom.js ➔ getClosest 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
/*global document */
2
3
export function nextSibling(parent, ele) {
4
  var next
5
  var found = false
6
  Array.prototype.forEach.call(parent.childNodes, (node) => {
7
    if(node.nodeName.indexOf('text') === -1) {
8
      if(found) {
9
        next = node
10
        found = false
11
      }
12
      if(node === ele) {
13
        found = true
14
      }
15
    }
16
  })
17
  
18
  return next
19
}
20
21
/**
22
 * Get closest DOM element up the tree that contains a class, ID, or data attribute
23
 * @param  {Node} elem The base element
24
 * @param  {String} selector The class, id, data attribute, or tag to look for
25
 * @return {Node} Null if no match
26
 */
27
export function getClosest(elem, selector) {
28
29
  var firstChar = selector.charAt(0)
30
31
    // Get closest match
32
  for ( ; elem && elem !== document; elem = elem.parentNode ) {
33
34
        // If selector is a class
35
    if ( firstChar === '.' ) {
36
      if ( elem.classList.contains( selector.substr(1) ) ) {
37
        return elem
38
      }
39
    }
40
41
        // If selector is an ID
42
    if ( firstChar === '#' ) {
43
      if ( elem.id === selector.substr(1) ) {
44
        return elem
45
      }
46
    } 
47
48
        // If selector is a data attribute
49
    if ( firstChar === '[' ) {
50
      if ( elem.hasAttribute( selector.substr(1, selector.length - 2) ) ) {
51
        return elem
52
      }
53
    }
54
55
        // If selector is a tag
56
    if ( elem.tagName.toLowerCase() === selector ) {
57
      return elem
58
    }
59
60
  }
61
62
  return false
63
64
}