Skip to content

Instantly share code, notes, and snippets.

@franklinjavier
Last active August 29, 2015 14:09
Show Gist options
  • Select an option

  • Save franklinjavier/7f2c6d0bd1e5a7c10887 to your computer and use it in GitHub Desktop.

Select an option

Save franklinjavier/7f2c6d0bd1e5a7c10887 to your computer and use it in GitHub Desktop.
Minimal A/B testing
/*
* Minimal A/B Testing
*
* @author Franklin Javier (@franklinjavier)
* @date Nov 2014
*
* @example ABTest('variant1, variant2'); // return one of these
*
*/
/**
* @type {string} variants Variants separated by commas
* Ex - ABTest('test1, teste2, test3, test4');
* @public
*/
function ABTest( variants ) {
/**
* O nome do cookie que sera utilizado
* @type {string}
* @private
*/
var cookieName = '_cookieName';
/**
* As variantes passadas por parametro
* @type {string}
* @private
*/
var alternatives = variants.split(',');
/**
* Checa se o seed esta gravado no cookie, se nao,
* gera um seed novo e grava no cookie
* @return {number} O seed.
* @private
*/
function makeSeed() {
var seed = readCookie( cookieName );
if ( ! seed ) {
seed = Math.floor( Math.random() * alternatives.length );
setCookie( cookieName, alternatives[ seed ], 30 );
}
return seed;
}
/**
* Grava um cookie
* @param {string} name Nome do cookie
* @param {number|string} value Valor do cookie
* @param {number} days Momento que o cookie ira expirar (em dias).
* @private
*/
function setCookie( name, value, days ) {
var expires = '';
if ( days ) {
var date = new Date();
date.setTime( date.getTime()+(days*24*60*60*1000) );
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + ' = ' + value+expires + '; path=/';
}
/**
* Le um cookie
* @param {string} name Nome do cookie
* @param {number|string} value Valor do cookie
* @private
*/
function readCookie( name ) {
var match;
return ( match = new RegExp('(?:^|; )'+ name +'=([^;]+)').exec( document.cookie ))
? window.unescape( match[ 1 ] )
: null;
}
/**
* Remove cookie
* @private
*/
function removeCookie() {
document.cookie = cookieName + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
return makeSeed();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment