Created
May 7, 2013 04:53
-
-
Save pamelafox/5530321 to your computer and use it in GitHub Desktop.
chooseVariant
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Retrieve the variant to display. Should only be called once to ensure | |
* no double-counting of show events. | |
* | |
* @return {number} | |
*/ | |
Experiment.prototype.chooseVariant = function() { | |
var self = this; | |
// Capture fail scenarios. | |
if (!self.valid) return 0; | |
// In dev mode, look for parameter override. | |
if (self.devMode) { | |
var chosen = Cookie.get("ab-" + self.name); | |
if (chosen !== null) { | |
chosen = parseInt(chosen, 10); | |
if (chosen >= 0 && chosen < self.weights.length) | |
return chosen; | |
self.console.error("Invalid variant: " + chosen); | |
} | |
} | |
// Compute hash key. | |
var key = self.userId + "_" + name; | |
// Extract lowest 32 bits of SHA-1 digest. | |
// (This could be optimized slightly by cutting out fromBits) | |
var digest = sjcl.codec.hex.fromBits(sjcl.hash.sha1.hash(key)); | |
var hashValue = parseInt(digest.substr(digest.length - 8), 16); | |
var maxHashValue = Math.pow(2, 32); | |
// Compute total weight. | |
var totalWeight = 0.0; | |
var i; | |
for (i = 0; i < self.weights.length; i++) | |
totalWeight += self.weights[i]; | |
var targetWeight = (hashValue / maxHashValue) * totalWeight; | |
// Identify chosen variant. | |
for (i = 0; i < self.weights.length; i++) { | |
targetWeight -= self.weights[i]; | |
if (targetWeight < 0) { | |
return i; | |
} | |
} | |
return self.weights.length - 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment