美文网首页
数组比较函数 ArrayDiff

数组比较函数 ArrayDiff

作者: copyLeft | 来源:发表于2022-12-15 11:40 被阅读0次
    
    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
      }
    }
    
    
    

    相关文章

      网友评论

          本文标题:数组比较函数 ArrayDiff

          本文链接:https://www.haomeiwen.com/subject/fmrrqdtx.html