all files / src/ fieldKeys.js

100% Statements 129/129
97.83% Branches 90/92
100% Functions 9/9
100% Lines 9/9
29 statements, 3 functions, 24 branches Ignored     
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 29×                                                                 17×        
function* generate(field, values, path = '') {
  const [all, key, rest] = /([^.]+)\.?(.+)?/.exec(field)
 
  if (/.+\[\]/.test(key)) {
    // is array key
    const noBrackets = key.substring(0, key.length - 2)
    const array = values && values[ noBrackets ]
    if (array && !Array.isArray(array)) {
      throw new Error(`Expected array value for ${path}${field}, but found ${typeof array}: ${JSON.stringify(array)}`)
    }
    if (array) {
      if (rest) {
        for (let index in array) {
          yield * generate(rest, array[ index ], `${path}${noBrackets}[${index}].`)
        }
      } else {
        for (let index in array) {
          yield `${path}${noBrackets}[${index}]`
        }
      }
    } else {
      yield `${path}${key}`
    }
  } else if (rest) {
    // need to recurse
    yield * generate(rest, values && values[ key ], `${path}${key}.`)
  } else {
    // value key
    yield `${path}${key}`
  }
}
 
/**
 * Iterates over all the fields specified by a fields array and store values.
 *
 * @param fields The fields array given to redux-form
 * @param values The current values of the form in the Redux store
 */
export default function* fieldKeys(fields = [], values = {}) {
  for (let field of fields) {
    yield * generate(field, values)
  }
}