Skip to content

Instantly share code, notes, and snippets.

@pamelafox
Created May 7, 2013 04:53
Show Gist options
  • Save pamelafox/5530321 to your computer and use it in GitHub Desktop.
Save pamelafox/5530321 to your computer and use it in GitHub Desktop.
chooseVariant
/**
* 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