Please explain the _ .baseUniq method in the lodash source code.

curiosity prompted me to take a look at the source code of lodash"s array deduplication method _ .uniq, which points to _ .baseUniq. The source code is as follows:

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 (PPindex < 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
}
There are a little more interference items in

, and I feel dizzy. Ask God for help to come up with an abbreviated version and explain the train of thought.

Source address of baseUniq: Link description


if you read it from uniq , the code only sends array , not iteratee,comparator

.

if the length of the array exceeds 200 , return array-> set-> array directly
and then make a judgment value = = value . At first glance, you will think that you will return true at first glance. This judgment is to filter the case of NaN , because const value = NaN Value = value / / false
if it is NaN , you will enter the includes method ( isNaN will be called internally)

the whole is to traverse the incoming array array . Each cycle checks whether the current value exists in the result array, there is skip, and there is no push

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

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

    outer:
    while (PPindex < 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
}

is there a big god to help me answer? The problem has sunk to the bottom.

Menu