JS数组求指定步长的补集

270 阅读1分钟
/* 
  @brief: 求出已知首尾大小、且知步长的数组
  @param: min首,max尾,step步长
  @return: Array
  @note: 参数必传
  @see: 
*/
const generateHeadAndTailArr = ({
  min,
  max,
  step
}) => Array.from({
  length: ((max - min) / step) + 1
}, (v, k) => min + k * step)
/* 
  @brief: 求补集
  @param: totle总集合,subset子集合,step步长
  @return: Array
  @note: 参数必传
  @see: generateHeadAndTailArr
*/
const takeComplement = ({
  totle,
  subset,
  step
} = {}) => {
  let surplus = [];
  subset.forEach((itemRange, index) => {
    const start = itemRange[0];
    const end = itemRange[itemRange.length - 1];
    const idx = totle.indexOf(start);
    const len = totle.indexOf(end) - idx;
    totle.splice(idx, len);
  });
  surplus = [...totle];
  let complement = [];
  let info = [];
  surplus.forEach((item, index) => {
    if (info[0] === undefined) {
      info[0] = item;
    }
    if (info[1] === undefined && index - 1 >= 0) {
      const prev = surplus[index - 1]
      const stepT = item - prev;
      if (stepT > step) {
        info[1] = prev;
        complement.push(generateHeadAndTailArr({
          min: info[0],
          max: info[1],
          step: 30
        }));
        info = [];
        info[0] = item;
      }
      if (surplus.length - 1 === index) {
        info[1] = item
        complement.push(generateHeadAndTailArr({
          min: info[0],
          max: info[1],
          step: 30
        }));
        info = [];
      }
    }
  });
  return complement
}
const tc = takeComplement({
  totle: Array.from({
    length: 48
  }, (v, k) => k * 30),
  subset: [
    [3 * 30, 4 * 30, 5 * 30],
    [20 * 30, 21 * 30],
    [30 * 30, 31 * 30, 32 * 30, 33 * 30, 34 * 30, 35 * 30, 36 * 30, 37 * 30, 38 * 30, 39 * 30, 40 * 30, 41 *
      30
    ],
    [42 * 30, 43 * 30, 44 * 30, 45 * 30, 46 * 30]
  ],
  step: 30
})
console.log(JSON.stringify(tc), `:::tc`)