Completed
Push — master ( cd3036...143160 )
by greg
49s
created

sourceAttr.js ➔ getKeys   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 6
nop 1
dl 0
loc 17
rs 8.8571
c 0
b 0
f 0
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
17
  Array.prototype.forEach.call(params.value, (pValue) => {
18
    if (isSelected(pValue, displayName, str)) {
19
      selected = "selected"
20
    }
21
  })
22
23
  return {
24
    hiddenVal: (typeof obj == 'object') ? JSON.stringify(obj).replace(/\'/g, '&quote;') : obj,
25
    selected: selected,
26
    val: displayName
27
  }
28
}
29
30
/**
31
 * return the value from a json obj of a nested attribute
32
 * @param  {Object} obj  the json object
33
 * @param  {string} path the path to object (dot notation)
34
 * @return {[type]}      the object containing the path object or undefined
35
 */
36
export function get(obj, path) {
37
  if (path == null) {
38
    return obj
39
  }
40
  return path.split('.').reduce(function(prev, curr) {
41
    return prev ? prev[curr] : undefined
42
  }, obj || this)
43
}
44
45
/**
46
 * replace the variables in str by values from obj
47
 * corresponding to keys
48
 * @param  {Object} obj    the json object
49
 * @param  {string} str    the string
50
 * @return {string}        the string with values
51
 */
52
export function prepareDisplay(obj, str = null) {
53
  var keys = getKeys(str)
54
  Array.prototype.forEach.call(keys, (key) => {
55
    var val = get(obj, key)
56
    var pattern = new RegExp('{{'+key+'}}|'+key, 'g')
57
    str = str.replace(pattern, val)
58
  })
59
60
  if (str == null) {
61
    str = obj
62
  }
63
64
  return str
65
}
66
67
/**
68
 * return array of variables {{variable}} extracted from str
69
 * @param  {string} str the string containing variables
70
 * @return {Array}     the array of variables
71
 */
72
export function getKeys(str){
73
  var regex = /\{\{(.*?)\}\}/g
74
  var variables = []
75
  var match
76
77
  while ((match = regex.exec(str)) !== null) {
78
    if (match[1] != null) {
79
      variables.push(match[1])
80
    }
81
  }
82
  
83
  if (variables.length == 0 && str != null) {
84
    variables.push(str)
85
  }
86
87
  return variables
88
}
89