You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

适用于50-50 A/B测试的差异化分组算法方案咨询

基于CustomerId的独立A/B分组方案(JS/TS实现)

核心思路

  • 将customerId与**唯一的feature标识(featureId)**结合作为哈希输入,确保不同feature的分组逻辑完全独立,避免奇偶判断导致的分组重合问题
  • 采用确定性哈希算法,保证同一用户在同一feature下的分组结果永久稳定
  • 通过哈希值的范围判断实现精准的50-50分组,也支持灵活调整分组比例

代码实现

/**
 * 为用户分配A/B测试分组
 * @param customerId 用户唯一标识(支持字符串或数字类型)
 * @param featureId 测试特征的唯一标识(如'checkout-ux-v2'、'homepage-banner')
 * @returns 分组结果:'A' 或 'B'
 */
function assignABTestGroup(customerId: string | number, featureId: string | number): 'A' | 'B' {
  // 拼接用户ID和特征ID,确保每个特征的分组独立
  const input = `${customerId}-${featureId}`;
  
  // 计算简单字符串哈希值(足够应对10个以内的测试场景)
  let hash = 0;
  for (let i = 0; i < input.length; i++) {
    const charCode = input.charCodeAt(i);
    hash = ((hash << 5) - hash) + charCode;
    hash = hash & hash; // 转换为32位整数
  }
  
  // 将哈希值映射到0-99的范围,实现50-50分组
  const normalizedValue = Math.abs(hash) % 100;
  return normalizedValue < 50 ? 'A' : 'B';
}

关键细节说明

  • 分组独立性:每个feature使用唯一的featureId(如'feature-1'、'feature-2'),同一用户在不同feature下的分组结果完全独立,不会出现重合情况
  • 稳定性:只要customerId和featureId不变,分组结果永久固定,符合A/B测试的确定性要求
  • 可扩展性:若需调整分组比例(比如30%进A组、70%进B组),只需修改判断条件为normalizedValue < 30即可
  • 兼容性:支持字符串或数字类型的customerId和featureId,适配不同系统的ID格式

使用示例

// 同一用户,不同feature的分组结果独立
console.log(assignABTestGroup(4, 'feature-1')); // 可能输出 'A'
console.log(assignABTestGroup(4, 'feature-2')); // 可能输出 'B'

// 同一用户同一feature,结果固定
console.log(assignABTestGroup(7, 'feature-1')); // 多次调用结果一致

内容的提问来源于stack exchange,提问作者mattsmith5

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 14:35:13