const crypto = require('crypto');
function generateABValue(userId, featureName, ratio) {
if (ratio > 1 || ratio < 0) {
throw new Error("Ratio must be between 0 and 1");
}
if(ratio === 0) return 'A';
if(ratio === 1) return 'B';
// Create a hash from the userId, featureName
const hash = crypto.createHash('sha1');
hash.update(userId + featureName);
const hashedValue = hash.digest('hex');
// Convert the last 2 characters of the hash into an integer and normalize to 0-1 range
const intValue = parseInt(hashedValue.slice(-2), 16);
const normalizedValue = intValue / 255;
//console.log({hashedValue, intValue, normalizedValue})
// Use the ratio to determine the group
return normalizedValue <= ratio ? 'B' : 'A';
}
function testDistribution(ratio, featureName) {
var countA = 0;
var countB = 0;
// Run the function 10000 times with different userIds
for (var i = 0; i < 10000; i++) {
var group = generateABValue('user' + i, featureName, ratio);
if (group === 'A') {
countA++;
} else if (group === 'B') {
countB++;
}
}
console.log('Group A: ' + countA);
console.log('Group B: ' + countB);
// console.log('Group: ' + generateABValue(62432877, featureName, ratio));
}
testDistribution(0.5, "ab_test_bnpl_ph")
// console.log('Groups: ' + generateABValue("62432877", "ab_test_fps", 0.5));