-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathABTest.js
93 lines (89 loc) · 2.46 KB
/
ABTest.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
'use strict'
function TestCase(name, weight, options) {
this.name = name;
this.weight = weight;
if (options) {
this.target = options.target || null;
this.CSS = options.CSS || {};
this.init = options.init || null;
this.callback = options.callback || null;
this.otherData = options.other || {};
}
};
function ABTest(name, identifier, testcases, options) {
if (arguments.length !== 3 && arguments.length !== 4) {
throw "Incorrect number of arguments.";
}
this.testName = name;
this.identifier = identifier;
this.testcases = testcases;
this.formData = new FormData();
this.formData.name = name;
if (options) {
for (var prop in options) {
if (options.hasOwnProperty(prop)) {
this[prop] = options[prop];
}
}
}
this.initTest = function() {
var weights = this.testcases.map(function(x) {return x.weight});
var sum = weights.reduce(function(x,y) {return x + y});
var groupVal = this.identifier % sum;
var total = 0;
var group = 0;
for (var i = 0; i < weights.length; i++) {
total += weights[i];
if (groupVal <= total) {
group = i;
break;
}
}
var testcase = this.testcases[group];
this.groupName = testcase.name;
if (testcase.target !== null) {
for (var prop in testcase.CSS) {
testcase.target.style[prop] = testcase.CSS[prop];
}
}
if (testcase.init !== null) {
testcase.init();
}
this.callback = testcase.callback;
}
this.sendTestData = function(otherData) {
if (this.callback) {
this.callback()
}
this.formData.identifier = this.identifier;
this.formData.group = this.groupName;
if (this.timestamp) {
this.formData.timestamp = (new Date()).toUTCString();
}
if (this.viewport) {
this.formData.viewport = {width: window.innerWidth, height: window.innerHeight}
}
if (this.userAgent) {
this.formData.userAgent = navigator.userAgent;
}
if (this.URL) {
this.formData.URL = window.location.href
}
if (otherData) {
for (var prop in otherData) {
this.formData[prop] = otherData[prop];
}
}
if (this.endpoint) {
if (navigator.sendBeacon) {
navigator.sendBeacon(this.endpoint, JSON.stringify(this.formData));
}
else {
var request = new XMLHttpRequest();
request.open('POST', this.endpoint, true);
request.send(this.formData);
}
}
return this.formData;
}
}