Learn more  » Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Bower components Debian packages RPM packages NuGet packages

skava / chain-able-deps   js

Repository URL to install this package:

Version: 6.0.4 

/ src / loop / reduce / reduceArrayToObj.ts

import toKey from '../../cast/toKey'
import { isNil, isObj } from '../../is'

// @TODO ~ also see reduceMap it has keyValReducer, can do `isPairs`
const defaultReduceArrayToObjIterator = (reduced, next, index) => {
  if (isObj(next)) Object.assign(reduced, next)
  else reduced[toKey(index)] = next

  return reduced
}

/**
 * @since 4.0.0
 * @version 5.0.0 <- added index
 *
 * @param {Array} array array to reduce to object
 * @param {Function} iterator function to call on reduced, with `next`
 * @return {Object} reduced array
 *
 *
 * @name reduceObj
 * @alias reduceObject
 * @alias toObj
 *
 * @see Chainable
 *
 * @TODO example
 * @TODO @curried 2
 */
export default function reduceArrayToObj(array, iterator) {
  if (isNil(iterator)) iterator = defaultReduceArrayToObjIterator

  let index = 0
  return array.reduce((reduced, next) => {
    iterator(reduced, next, index)
    return reduced
  }, {})
}