Completed
Push — master ( 03cb87...68903a )
by Michael
28s queued 12s
created

getUserIdentifier.js ➔ getIdentifier   A

Complexity

Conditions 5

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 15
dl 0
loc 25
rs 9.1832
c 0
b 0
f 0
1
function generateIdentifier() {
2
  const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
3
  let text = ''
4
5
  for (let i = 0; i < 20; i++) {
6
    text += possible.charAt(Math.floor(Math.random() * possible.length))
7
  }
8
9
  return text
10
}
11
12
export default function getIdentifier(userIdentifier) {
13
  if (userIdentifier || userIdentifier === 0) {
14
    return String(userIdentifier)
15
  }
16
17
  if (typeof window === 'undefined' || !('localStorage' in window)) {
18
    return null
19
  }
20
21
  const key = '__ab_experiment_identifier__'
22
23
  try {
24
    userIdentifier = localStorage.getItem(key)
0 ignored issues
show
Bug introduced by
The variable localStorage seems to be never declared. If this is a global, consider adding a /** global: localStorage */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
Bug introduced by
The variable localStorage was not defined.
Loading history...
25
    userIdentifier = userIdentifier && String(userIdentifier)
26
27
    if (!userIdentifier) {
28
      userIdentifier = generateIdentifier()
29
      localStorage.setItem(key, userIdentifier)
0 ignored issues
show
Bug introduced by
The variable localStorage was not defined.
Loading history...
30
    }
31
  } catch (exception) {
32
    return null
33
  }
34
35
  return userIdentifier
36
}
37