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

如何编写支持n种变体的笛卡尔积函数生成按钮组件模板?

生成组件变体所有组合模板的可复用笛卡尔积函数

给定定义组件变体的对象(如按钮的colorMode和size可选值),我们可以通过两步实现可复用的解决方案:先生成所有变体的笛卡尔积组合,再将组合转换为目标模板字符串。

1. 核心笛卡尔积生成函数

这个函数接收任意结构的变体对象(支持n种变体),返回所有可能的键值对组合数组:

function getCartesianProduct(variants) {
  const entries = Object.entries(variants);
  let product = [{}];

  for (const [key, values] of entries) {
    product = product.flatMap(combination => 
      values.map(value => ({ ...combination, [key]: value }))
    );
  }

  return product;
}

2. 按钮模板生成函数

基于笛卡尔积结果,将每个组合转换为<button>模板字符串:

function generateButtonTemplates(variants) {
  const combinations = getCartesianProduct(variants);
  
  return combinations.map(combination => {
    const attributes = Object.entries(combination)
      .map(([key, value]) => `${key}="${value}"`)
      .join(' ');
    return `<button ${attributes}>button</button>`;
  });
}

测试使用

用你提供的buttonVariants测试:

const buttonVariants = {
  colorMode: ['on-dark','on-light'],
  size: ['small','medium','large']
};

// 输出期望的模板数组
console.log(generateButtonTemplates(buttonVariants));

这个方案完全支持扩展任意数量的变体,比如新增shape: ['round', 'square'],函数会自动生成包含该属性的所有组合模板。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 04:36:05