all files / src/ getValues.js

97.37% Statements 37/38
93.55% Branches 29/31
100% Functions 6/6
96.97% Lines 32/33
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57          208×   255× 255× 255× 255×     255×   23× 23× 23× 15×   23× 23× 15× 14×   15× 21× 20×   21×       232×   12× 12× 12× 10×   12×   220×       120×   222× 221×        
/**
 * Given a state[field], get the value.
 *  Fallback to .initialValue when .value is undefined to prevent double render/initialize cycle.
 *  See {@link https://github.com/erikras/redux-form/issues/621}.
 */
const itemToValue =
  ({value, initialValue}) => typeof value !== 'undefined' ? value : initialValue;
 
const getValue = (field, state, dest) => {
  const dotIndex = field.indexOf('.');
  const openIndex = field.indexOf('[');
  const closeIndex = field.indexOf(']');
  Iif (openIndex > 0 && closeIndex !== openIndex + 1) {
    throw new Error('found [ not followed by ]');
  }
  if (openIndex > 0 && (dotIndex < 0 || openIndex < dotIndex)) {
    // array field
    const key = field.substring(0, openIndex);
    let rest = field.substring(closeIndex + 1);
    if (rest[0] === '.') {
      rest = rest.substring(1);
    }
    const array = state && state[key] || [];
    if (rest) {
      if (!dest[key]) {
        dest[key] = [];
      }
      array.forEach((item, index) => {
        if (!dest[key][index]) {
          dest[key][index] = {};
        }
        getValue(rest, item, dest[key][index]);
      });
    } else {
      dest[key] = array.map(itemToValue);
    }
  } else if (dotIndex > 0) {
    // subobject field
    const key = field.substring(0, dotIndex);
    const rest = field.substring(dotIndex + 1);
    if (!dest[key]) {
      dest[key] = {};
    }
    getValue(rest, state && state[key] || {}, dest[key]);
  } else {
    dest[field] = state[field] && itemToValue(state[field]);
  }
};
 
const getValues = (fields, state) =>
  fields.reduce((accumulator, field) => {
    getValue(field, state, accumulator);
    return accumulator;
  }, {});
 
export default getValues;