-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
119 lines (98 loc) · 2.95 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*!
Copyright (c) 2018 Tacnoman.
Licensed under the MIT License (MIT), see
https://github.com/tacnoman/googleAnalyticsAb
*/
/* global define */
(function() {
var googleAnalyticsAB = {
storage: typeof localStorage !== 'undefined' ? localStorage : {},
create: function(config) {
this.init(config);
if(!this._isAlreadySorted()) {
if(this._sortIsInCurrentTest()) {
this.storage[this.name] = this._sortOneOption().name;
} else {
this.storage[this.name] = false;
}
}
if(!this.storage[this.name]) return;
var option = this._getCurrentOption();
option['convert'] = this.convert.bind(this);
this.selectedOption = option;
if(config.run && typeof config.run === 'function') {
config.run.call(this, option);
}
this.registerPageViewEvent();
return this;
},
init: function(config) {
this.name = config.name;
this.percentage = config.percentage || 80;
this.options = config.options.map(function(option) {
return Object.assign({}, {
weight: 1
}, option);
});
},
convert: function() {
if(typeof ga !== 'function') {
console.error('You must have the ga script in your page');
return false;
}
this.sendEvent('convert');
return true;
},
sendEvent: function(action) {
ga('send', {
hitType: 'event',
eventCategory: 'googleAnalyticsAB-' + this.name,
eventAction: action,
eventLabel: this.selectedOption.name,
eventValue: 1,
});
},
registerPageViewEvent: function() {
this.sendEvent('view');
},
_getCurrentOption: function() {
var alternativeName = this.storage[this.name];
for(var i=0, qt=this.options.length; i<qt; i++) {
var currentOption = this.options[i];
if(currentOption.name === alternativeName) {
return currentOption;
}
}
},
_isAlreadySorted: function() {
return !(typeof this.storage[this.name] === 'undefined');
},
_sortIsInCurrentTest: function() {
var sorted = this._randomBetween(0, 100);
return sorted < this.percentage;
},
_randomBetween: function(min, max) {
return Math.floor(Math.random() * max) + min;
},
_sortOneOption: function() {
var total = this.options.reduce(function(op1, op2) {
return op1.weight + op2.weight;
});
var sorted = this._randomBetween(1, total);
for(var i=0,qt=this.options.length; i<qt; i++) {
sorted -= this.options[i].weight;
if(sorted <= 0) return this.options[i];
}
}
};
if (typeof define === 'function' && define.amd) {
// AMD
define('googleAnalyticsAB', [], googleAnalyticsAB);
} else if (typeof exports === 'object') {
// CommonJS
module.exports = googleAnalyticsAB;
} else {
// Browser globals
window.googleAnalyticsAB = googleAnalyticsAB;
}
})();