Skip to content

Instantly share code, notes, and snippets.

@shanewholloway
Created May 22, 2013 22:43
Show Gist options
  • Save shanewholloway/5631544 to your computer and use it in GitHub Desktop.
Save shanewholloway/5631544 to your computer and use it in GitHub Desktop.
Small and simple A/B testing tool. - Only supports two option 50/50 tests. On purpose. - Open-ended backend tracking. - Uses localStorage instead of cookies to cut down on bandwidth waste.
// Licensed [CC-BY Shane Holloway](http://creativecommons.org/licenses/by/3.0/)
function ab_tracker(track) {
"use strict";
ab_test.store = window.localStorage || null;
ab_test.prefix = 'ab_test::'
ab_test.track = track
if (typeof track !== 'function')
throw new Error('`track` must be a function');
var truth = {'true':true, 'false':false, null:null};
return ab_test
function ab_test(key, setupTestFn) {
var obj, s=ab_test.store,
pk=ab_test.prefix+key,
a=s && truth[s.getItem(pk)];
if (a===null)
try{ s.setItem(pk, a=0.5<Math.random()) } catch(err) {}
ab_test.track(pk, obj={ab:(a?'A':'B'), a:a, b:!a, key:key, pk:pk})
if (setupTestFn) setupTestFn(!a, obj)
return obj }
}
var ab_test = ab_tracker(function(pk, obj) {
// connect to your test metric backend collector
analytics.track(pk, obj)
})
ab_test('20130421 test idea', function(test, obj) {
// enable & perform setup…
if (test) // for *Experiment*
document.body.className+=' test_idea';
else ; // for *Control*
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment