Skip to content

Instantly share code, notes, and snippets.

@kristian76
Last active November 25, 2016 16:44
Show Gist options
  • Save kristian76/93b247eca1df07f91961e9d1a450ef62 to your computer and use it in GitHub Desktop.
Save kristian76/93b247eca1df07f91961e9d1a450ef62 to your computer and use it in GitHub Desktop.
AB split testing in JS
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<script>
var AB = {
_c: '',
_v: [],
setup: function(c, v) {
this._c = c;
this._v = v;
var _r = this.getRandomInt(0, this._v.length);
if (typeof this.getCookie(this._c) == 'undefined') {
this.setCookie(this._c, _r.toString());
}
return this;
},
run: function() {
var _cv = parseInt(this.getCookie(this._c)),
_t = this._v[_cv];
_t.campaign = this._c;
_t.sample = _cv;
_t.test(_t);
},
getRandomInt: function(mi, ma) {
return Math.floor(Math.random() * (ma - mi)) + mi;
},
setCookie: function(key, val, expire, path) {
var _k = key || null,
_v = val || null,
_e = expire || null,
_p = path || '/';
if (_e) {
var d = new Date();
d.setTime(d.getTime() + (_e * 24 * 60 * 60 * 1000));
_e = d.toGMTString();
}
document.cookie = _k+'='+_v+'; expires='+_e+'; path='+_p;
},
getCookie: function(key) {
var _v = [],
_c = document.cookie.split(';') || [],
_n = RegExp('^\\s*'+key+'=\\s*(.*?)\\s*$');
for (var i = 0; i < _c.length; i++) {
var _f = _c[i].match(_n);
_f&&_v.push(_f[1]);
}
return _v.pop();
},
};
AB.setup('something', [
{
name: 'tis_a',
test: function(obj) {
console.log('variant_a', obj);
}
},
{
name: 'tis_b',
test: function(obj) {
console.log('variant_b', obj);
}
}
]).run();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment