_.union([arrays])


49

_.union([arrays])
_.union接收多个数组为参数,创建一个去重后的数组,使用SameValueZero规则来比较元素是否相等

参数

[arrays] (...Array): 需要处理的多个数组

返回值

(Array): 返回连起来的去重后的数组

例子

_.union([2], [1, 2]);
// => [2, 1]

源代码:

大数组的缓存机制之前看过了,省略

import baseFlatten from './.internal/baseFlatten.js'
import baseUniq from './.internal/baseUniq.js'
import isArrayLikeObject from './isArrayLikeObject.js'

/**
 * Creates an array of unique values, in order, from all given arrays using
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons.
 *
 * @since 0.1.0
 * @category Array
 * @param {...Array} [arrays] The arrays to inspect.
 * @returns {Array} Returns the new array of combined values.
 * @see difference, unionBy, unionWith, without, xor, xorBy
 * @example
 *
 * union([2, 3], [1, 2])
 * // => [2, 3, 1]
 */
//接收多个数组为参数,创建一个去重后的数组,使用SameValueZero规则来比较元素是否相等
function union(...arrays) {
  return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true))
  //将参数数组展开一层后形成的数组传递给baseUniq处理
}

export default union

baseUniq

import SetCache from './SetCache.js'
import arrayIncludes from './arrayIncludes.js'//判断数组是否包含给定值
import arrayIncludesWith from './arrayIncludesWith.js'//判断数组是否包含给定值,区别是它的comparator需要作为参数传入
import cacheHas from './cacheHas.js'
import createSet from './createSet.js'
import setToArray from './setToArray.js'

/** Used as the size to enable large array optimizations. */
const LARGE_ARRAY_SIZE = 200

/**
 * The base implementation of `uniqBy`.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {Function} [iteratee] The iteratee invoked per element.
 * @param {Function} [comparator] The comparator invoked per element.
 * @returns {Array} Returns the new duplicate free array.
 */
//uniqBy的基础实现,数组去重
function baseUniq(array, iteratee, comparator) {
  let index = -1//循环索引
  let includes = arrayIncludes//类似数组的includes方法,判断数组是否包含给定值
  let isCommon = true//有没有自定义比较器或者有没有开启缓存的标记

  const { length } = array//数组长度
  const result = []//结果数组
  let seen = result//临时数组,用来存入不重复的数组元素值

  if (comparator) {//如果传递了自定义比较器,incledes方法就用arrayIncludesWith
    isCommon = false
    includes = arrayIncludesWith
  }
  else if (length >= LARGE_ARRAY_SIZE) {//如果数组长度超过200,就设置缓存
    const set = iteratee ? null : createSet(array)//如果没有iteratee和comparator,就直接使用ES6的set类型去重
    if (set) {//如果可以用set类型去重,直接新建set对象然后再转换成数组后返回结果
      return setToArray(set)
    }
    isCommon = false//否则开启数组缓存
    includes = cacheHas
    seen = new SetCache
  }
  else {//如果没有自定义比较器,数组长度也没有超过200
    seen = iteratee ? [] : result
  }
  outer:
  while (++index < length) {//遍历数组
    let value = array[index]//当前元素
    const computed = iteratee ? iteratee(value) : value//iteratee处理后的当前元素

    value = (comparator || value !== 0) ? value : 0//如果没有传递comparator,将-0变为0
    if (isCommon && computed === computed) {//如果没有传递自定义比较器,或者没有开启缓存,并且computed不是NaN
      let seenIndex = seen.length//seen数组的长度
      while (seenIndex--) {//遍历seen数组,如果有和当前值一样的,就跳出本次循环直接进行下一次
        if (seen[seenIndex] === computed) {
          continue outer
        }
      }
      if (iteratee) {//如果有iteratee参数,seen结尾插入当前不重复的元素
        seen.push(computed)
      }
      result.push(value)//结果数组结尾插入当前不重复的元素
    }
    else if (!includes(seen, computed, comparator)) {//如果有自定义比较器或者开启了缓存,并且seen中没有当前元素
      if (seen !== result) {//开启缓存的情况seen数组要插入新值
        seen.push(computed)
      }
      result.push(value)//结果数组插入新值
    }
  }
  return result
}

export default baseUniq

createSet

import setToArray from './setToArray.js'

/** Used as references for various `Number` constants. */
const INFINITY = 1 / 0

/**
 * Creates a set object of `values`.
 *
 * @private
 * @param {Array} values The values to add to the set.
 * @returns {Object} Returns the new set.
 */
//根据给定数组创建set对象
const createSet = (Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY)
  ? (values) => new Set(values)
  : () => {}
  //如果有Set类型,并且Set初始化时空白位置会赋值为undefined不会跳过,就返回新实例化Set对象的一个方法
  //否则返回一个什么都不做的方法

export default createSet

setToArray

/**
 * Converts `set` to an array of its values.
 *
 * @private
 * @param {Object} set The set to convert.
 * @returns {Array} Returns the values.
 */
//将一个set对象转换为一个数组
function setToArray(set) {
  let index = -1//循环索引
  const result = new Array(set.size)//结果数组

  set.forEach((value) => {//遍历set赋值给结果数组
    result[++index] = value
  })
  return result
}

export default setToArray

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM