import { uuidv4 } from '@firebase/util';

/**
 * Converts an array in to an object with the id as the key.
 * @param arr the array of objects
 * @returns object with the id as the key
 */
export function fromArray(arr: any[], idKey = 'id', valueKey?: 'all' | string) {
  return arr.reduce((obj, item) => {
    let value = item;
    if (valueKey && valueKey !== 'all') {
      // fallback to item if valueKey is not found
      value = item[valueKey];
    }
    if (item[idKey]) {
      obj[item[idKey]] = value;
    } else {
      if (typeof item === 'string') {
        obj[item] = value;
      } else {
        obj[uuidv4()] = value;
      }
    }

    return obj;
  }, {});
}
