Completed
Push — master ( 20c81d...5437b2 )
by greg
02:42
created

sourceAttr.js ➔ sourceAttr   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 3
c 1
b 1
f 0
nc 4
nop 2
dl 0
loc 21
rs 9.3142

1 Function

Rating   Name   Duplication   Size   Complexity  
A sourceAttr.js ➔ ... ➔ ??? 0 5 2
1
export function isSelected(value, display, str) {
2
  var selected = false
3
4
  var pDisplay = prepareDisplay(value, str)
5
  if (pDisplay === display) {
6
    selected = true
7
  }
8
9
  return selected
10
}
11
12
export default function sourceAttr(obj, params) {
13
  var str = params.display
14
  var selected = ''
15
  var displayName = prepareDisplay(obj, str)
16
  var values = params.value
17
  if(Object.prototype.toString.call(params.value) !== '[object Array]') {
18
    values = [params.value]
19
  }
20
21
  Array.prototype.forEach.call(values, (pValue) => {
22
    if (isSelected(pValue, displayName, str)) {
23
      selected = 'selected'
24
    }
25
  })
26
27
  return {
28
    hiddenVal: (typeof obj == 'object') ? JSON.stringify(obj).replace(/\'/g, '&quote;') : obj,
29
    selected: selected,
30
    val: displayName
31
  }
32
}
33
34
/**
35
 * return the value from a json obj of a nested attribute
36
 * @param  {Object} obj  the json object
37
 * @param  {string} path the path to object (dot notation)
38
 * @return {[type]}      the object containing the path object or undefined
39
 */
40
export function get(obj, path) {
41
  if (path == null) {
42
    return obj
43
  }
44
  return path.split('.').reduce(function(prev, curr) {
45
    return prev ? prev[curr] : undefined
46
  }, obj || this)
47
}
48
49
/**
50
 * replace the variables in str by values from obj
51
 * corresponding to keys
52
 * @param  {Object} obj    the json object
53
 * @param  {string} str    the string
54
 * @return {string}        the string with values
55
 */
56
export function prepareDisplay(obj, str = null) {
57
  var keys = getKeys(str)
58
  Array.prototype.forEach.call(keys, (key) => {
59
    var val = get(obj, key)
60
61
    var pattern = new RegExp('{{'+key+'}}|'+key, 'g')
62
    str = str.replace(pattern, val)
63
  })
64
    // console.log('params.value', params.value)
65
66
  if (str == null) {
67
    str = obj
68
  }
69
70
  return str
71
}
72
73
/**
74
 * return array of variables {{variable}} extracted from str
75
 * @param  {string} str the string containing variables
76
 * @return {Array}     the array of variables
77
 */
78
export function getKeys(str){
79
  var regex = /\{\{(.*?)\}\}/g
80
  var variables = []
81
  var match
82
83
  while ((match = regex.exec(str)) !== null) {
84
    if (match[1] != null) {
85
      variables.push(match[1])
86
    }
87
  }
88
  
89
  if (variables.length == 0 && str != null) {
90
    variables.push(str)
91
  }
92
93
  return variables
94
}
95