'use strict';

var nestedValue = require('../helpers/nestedValue');

module.exports = function keyBy(key) {
  var collection = {};

  if (typeof key === 'function') {
    this.items.forEach(function (item) {
      collection[key(item)] = item;
    });
  } else {
    this.items.forEach(function (item) {
      var keyValue = nestedValue(item, key);

      collection[keyValue || ''] = item;
    });
  }

  return new this.constructor(collection);
};