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
}
}
网友评论