数组比较函数 ArrayDiff


function defaultCheck (source, target) {
  return source === target
}

const MAX_RANGE = 10000

/**
 * 数组数据比对
 * @summary
 * 比较数组差异,筛选出:
 *  1.相同项 ( 未改变 )
 *  2.旧的不同项 (已删除)
 *  3.新加入项 (新添加)
 * 用于多选数组数据比较
 * 注意:限制了最大便利数 MAX_RANGE
 * @param {*} oldList 旧数据
 * @param {*} newList 新数据
 * @param {*} check 校验函数
 * @returns
 * - someList
 * - invalidList
 * - addList
 */
export default function arrayDiffe (oldList = [], newList = [], check = defaultCheck) {
  let count = MAX_RANGE
  const nList = [...newList]
  const oList = [...oldList]

  const someList = []
  const invalidList = []
  while (oList.length && !!count) {
    count -= 1
    const current = oList.pop()
    const index = nList.findIndex(i => check(i, current))
    if (index !== -1) {
      nList.splice(index, index)
      someList.push(current)
      continue
    }
    invalidList.push(current)
  }

  return {
    someList,
    invalidList,
    addList: nList
  }
}


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容