_.countBy(collection, [iteratee=_.identity])

65

_.countBy(collection, [iteratee=_.identity])
_countBy创建一个对象,对数组或者对象的每个元素或属性调用iteratee迭代器后生成这个对象的键,键的值是这个键出现的次数
iteratee支持传递属性名或者属性路径

参数

collection (Array|Object): 需要遍历的集合
[iteratee=_.identity] (Function): 转变键值的遍历器

返回值

(Object): 返回存储键累计值的对象

例子

 

_.countBy([6.1, 4.2, 6.3], Math.floor);
// => { '4': 1, '6': 2 }
 
// The `_.property` iteratee shorthand.
_.countBy(['one', 'two', 'three'], 'length');
// => { '3': 2, '5': 1 }

 

源代码:

import baseAssignValue from './.internal/baseAssignValue.js'
import reduce from './reduce.js'

/** Used to check objects for own properties. */
const hasOwnProperty = Object.prototype.hasOwnProperty

/**
 * Creates an object composed of keys generated from the results of running
 * each element of `collection` thru `iteratee`. The corresponding value of
 * each key is the number of times the key was returned by `iteratee`. The
 * iteratee is invoked with one argument: (value).
 *
 * @since 0.5.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The iteratee to transform keys.
 * @returns {Object} Returns the composed aggregate object.
 * @example
 *
 * const users = [
 *   { 'user': 'barney', 'active': true },
 *   { 'user': 'betty', 'active': true },
 *   { 'user': 'fred', 'active': false }
 * ]
 *
 * countBy(users, 'active');
 * // => { 'true': 2, 'false': 1 }
 */
//创建一个对象,对数组或者对象的每个元素或属性调用iteratee迭代器后生成这个对象的键,键的值是这个键出现的次数
//iteratee支持传递属性名或者属性路径
function countBy(collection, iteratee) {
  return reduce(collection, (result, value, key) => {//调用reduce累加器
    key = iteratee(value)
    if (hasOwnProperty.call(result, key)) {//如果结果对象上已经有当前key,key对应的值累加1
      ++result[key]
    } else {//如果结果对象上没有当前key,就用baseAssignValue给结果对象上新增key,值为1
      baseAssignValue(result, key, 1)
    }
    return result
  }, {})
}

export default countBy

baseAssignValue

/**
 * The base implementation of `assignValue` and `assignMergeValue` without
 * value checks.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */
//assignValue和assignMergeValue的基础实现
function baseAssignValue(object, key, value) {
  if (key == '__proto__') {//如果key是__proto__,就用Object.defineProperty设置
    Object.defineProperty(object, key, {
      'configurable': true,
      'enumerable': true,
      'value': value,
      'writable': true
    })
  } else {//否则直接设置
    object[key] = value
  }
}

export default baseAssignValue

reduce

import arrayReduce from './.internal/arrayReduce.js'
import baseEach from './.internal/baseEach.js'
import baseReduce from './.internal/baseReduce.js'

/**
 * Reduces `collection` to a value which is the accumulated result of running
 * each element in `collection` thru `iteratee`, where each successive
 * invocation is supplied the return value of the previous. If `accumulator`
 * is not given, the first element of `collection` is used as the initial
 * value. The iteratee is invoked with four arguments:
 * (accumulator, value, index|key, collection).
 *
 * Many lodash methods are guarded to work as iteratees for methods like
 * `reduce`, `reduceRight`, and `transform`.
 *
 * The guarded methods are:
 * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
 * and `sortBy`
 *
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {*} [accumulator] The initial value.
 * @returns {*} Returns the accumulated value.
 * @see reduceRight, transform
 * @example
 *
 * reduce([1, 2], (sum, n) => sum + n, 0)
 * // => 3
 *
 * reduce({ 'a': 1, 'b': 2, 'c': 1 }, (result, value, key) => {
 *   (result[value] || (result[value] = [])).push(key)
 *   return result
 * }, {})
 * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
 */
//将每一个集合中的元素通过iteratee处理后的结果累加到一个值,每一次连续的调用的累加值都是上一次的返回值。如果初始累加值没有提供,就使用第一次循环的返回值
function reduce(collection, iteratee, accumulator) {
  const func = Array.isArray(collection) ? arrayReduce : baseReduce//判断collection参数是数组还是其他类型,如果是数组调用arrayReduce,否则baseReduce
  const initAccum = arguments.length < 3
  return func(collection, iteratee, accumulator, initAccum, baseEach)
}

export default reduce
arrayReduce
/**
 * A specialized version of `reduce` for arrays.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {*} [accumulator] The initial value.
 * @param {boolean} [initAccum] Specify using the first element of `array` as
 *  the initial value.
 * @returns {*} Returns the accumulated value.
 */
//为数组类型数据提供的reduce方法
function arrayReduce(array, iteratee, accumulator, initAccum) {
  let index = -1//循环索引
  const length = array == null ? 0 : array.length//数组长度

  if (initAccum && length) {//如果没有提供累加器初始值,且数组至少有一个元素,累加器初始值就是数组第一个元素
    accumulator = array[++index]
  }
  while (++index < length) {//循环累加
    accumulator = iteratee(accumulator, array[index], index, array)
  }
  return accumulator
}

export default arrayReduce

baseReduce

/**
 * The base implementation of `reduce` and `reduceRight` which iterates
 * over `collection` using `eachFunc`.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {*} accumulator The initial value.
 * @param {boolean} initAccum Specify using the first or last element of
 *  `collection` as the initial value.
 * @param {Function} eachFunc The function to iterate over `collection`.
 * @returns {*} Returns the accumulated value.
 */
//reduce基础实现,使用eachFunc方法执行累加的方法
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
  eachFunc(collection, (value, index, collection) => {
    accumulator = initAccum
      ? (initAccum = false, value)
      : iteratee(accumulator, value, index, collection)
      //如果没有提供累加初始值,就用第一个元素作为初始值
  })
  return accumulator
}

export default baseReduce
baseEach
import baseForOwn from './baseForOwn.js'
import isArrayLike from '../isArrayLike.js'

/**
 * The base implementation of `forEach`.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array|Object} Returns `collection`.
 */
//forEach的基础实现
//collection被迭代遍历的对象,iteratee遍历器
function baseEach(collection, iteratee) {
  if (collection == null) {//如果collection为空,直接返回原对象
    return collection
  }
  if (!isArrayLike(collection)) {//如果collection不是array-like对象,就调用baseForOwn处理
    return baseForOwn(collection, iteratee)
  }
  const length = collection.length//对象长度
  const iterable = Object(collection)
  let index = -1//循环索引

  while (++index < length) {//循环调用iteratee方法
    if (iteratee(iterable[index], index, iterable) === false) {
      break
    }
  }
  return collection
}

export default baseEach

 

posted @ 2018-10-27 23:11  hahazexia  阅读(1415)  评论(0)    收藏  举报