1

好奇心促使下看了 lodash 的数组去重方法 _.uniq 的源码,它又指向了_.baseUniq,源码如下:

function baseUniq(array, iteratee, comparator) {
  let index = -1
  let includes = arrayIncludes
  let isCommon = true

  const { length } = array
  const result = []
  let seen = result

  if (comparator) {
    isCommon = false
    includes = arrayIncludesWith
  }
  else if (length >= LARGE_ARRAY_SIZE) {
    const set = iteratee ? null : createSet(array)
    if (set) {
      return setToArray(set)
    }
    isCommon = false
    includes = cacheHas
    seen = new SetCache
  }
  else {
    seen = iteratee ? [] : result
  }
  outer:
  while (++index < length) {
    let value = array[index]
    const computed = iteratee ? iteratee(value) : value

    value = (comparator || value !== 0) ? value : 0
    if (isCommon && computed === computed) {
      let seenIndex = seen.length
      while (seenIndex--) {
        if (seen[seenIndex] === computed) {
          continue outer
        }
      }
      if (iteratee) {
        seen.push(computed)
      }
      result.push(value)
    }
    else if (!includes(seen, computed, comparator)) {
      if (seen !== result) {
        seen.push(computed)
      }
      result.push(value)
    }
  }
  return result
}

里面的干扰项略多,感觉被绕晕了,求大神帮忙出个缩略版的,并解释一下思路。

baseUniq 的源码地址:链接描述

2月26日提问

查看全部 2 个回答

1

已采纳

你是从 uniq 看过去的话 代码就是只传了array没有传iteratee,comparator

开始判断一下数组的长度如果超出 200, 就直接返回 array -> set -> array
然后进行了一个判断 value === value,乍一看会以为怎么样都会返回 true,这个判断是为了过滤 NaN 的情况,因为 const value = NaN; value === value // false
如果是NaN的情况会进入includes方法(内部会调用isNaN进行判断)

整体就是 遍历传入数组 array ,每次循环检查当前值在 result 数组中是否存在,存在跳过,不存在 push

function baseUniq(array) {
    let index = -1
    const { length } = array
    const result = []

    if (length >= 200) {
        const set = createSet(array)
        return setToArray(set)
    }

    outer:
    while (++index < length) {
        const value = array[index]
        if (value === value) {
            let resultIndex = result.length
            while (resultIndex--) {
                if (result[resultIndex] === value) {
                    continue outer
                }
            }
            result.push(value)
        } else if (!includes(seen, value)) {
            result.push(value)
        }
    }
    return result
}

推广链接