嵌套循环,验证是继续循环还是开始下一次迭代

Nested loop with validation on whether to continue the loop or begin the next iteration

我有一个这样的对象(为简单起见,用虚拟数据替换,在实际情况下,每个整数元素都是一个对象):

const dummyObject = {
    A: [
        [ 1, 2 ],
        [ 3, 4 ],
        [ 5, 6 ]
    ],
    B: [
        [ 7 ],
        [ 8 ]
    ],
    C: [
        [ 9, 10, 11 ],
        [ 12, 13, 14 ],
        [ 15, 16, 17 ]
    ]
}

注意每个 属性 A, BC 中的所有整数数组(内部数组)都是等长的,并且外部数组的长度 (包含整数数组)可能会有所不同。也可以有不同数量的属性 (D, E, ...)

现在我想以特定方式遍历数组,其中每次迭代形成一个结果数组:

//
// Result arrays (18 total):
//

// 1st iteration
[ 1, 2, 7, 9, 10, 11 ]
// 2nd iteration
[ 1, 2, 7, 12, 13, 14 ]
// 3rd
[ 1, 2, 7, 15, 16, 17 ]
// 4th
[ 1, 2, 8, 9, 10, 11 ]
// 5th
[ 1, 2, 8, 12, 13, 14 ]
// ...
// 18th and final iteration
[ 5, 6, 8, 15, 16, 17 ]

我可以设法执行此循环,但每次我将整数数组附加到结果数组时,我都想验证结果数组。如果验证失败,我想丢弃结果数组并开始下一次迭代。示例:

//
// Same loop, but validate result array after every update.
//

// 1st iteration: Result array fails validation after the "[ 7 ]" array is added to it,
// discard this result array and start the 2nd iteration immediately.
[ 1, 2, 7 ]
// 2nd iteration
// ...

您可以使用笛卡尔积并传递自定义函数以在将每一行添加到结果之前对其进行验证。

const data = {
  A: [
    [1, 2],
    [3, 4],
    [5, 6]
  ],
  B: [
    [7],
    [8]
  ],
  C: [
    [9, 10, 11],
    [12, 13, 14],
    [15, 16, 17]
  ]
}

function iterate(data, validate = () => {}) {
  const result = [];

  function f(values, n = 0, c = []) {
    if (n === values.length) {
      const row = c.flat();
      const isValid = validate(row)
      if (isValid) result.push(row);
      else console.log('not valid', row)
      return;
    }

    for (let i = 0; i < values[n].length; i++) {
      c[n] = values[n][i]
      f(values, n + 1, c)
    }
  }

  f(Object.values(data))
  return result;
}

const validator = data => data.every(e => e !== 7)
const result = iterate(data, validator);
console.log(result)