sku组合算法

151 阅读1分钟

将原始数据转化成二维数组,根据二维数组的值对二维数组加一以及进一操作,最终得到组合的结果

const skuList = [
  ['red', 'green', 'black'],
  ['small', 'big'],
  [12, 25, 54, 56],
  ['12g', '25g', '2g', '8g']
]
function combineProduct (sku) {
    let skuT = [[]]
    const arr = sku.map(col => {
      skuT[0].push(col[0])
      return col.length - 1
    })
    const l = arr.length
    let o = Array.from({length: l}).fill(0)
    const sum = arr.reduce((total, currentValue) => {
      return total * (currentValue + 1)
    }, 1)
    let count = skuT.length
    while(sum !== count) {
        let begin = true
        let j = l - 1
        while (begin) {
            if (j < 0) {
                begin = false
                break
            }
            if (o[j] < arr[j]) {
                o[j] += 1
                begin = false
            } else {
                o[j] = 0
                j--
            }
        }
        count++
        skuT[count - 1] = []
        o.forEach((col, index) => {
          skuT[count - 1].push(sku[index][col])
        })
    }
    return skuT
}
console.time('渲染时间:')
const a = combineProduct(skuList)
console.timeEnd('渲染时间:')
console.log(a)