all files / src/structure/plain/ setIn.js

100% Statements 41/41
100% Branches 22/22
100% Functions 6/6
100% Lines 15/15
8 statements, 1 function, 6 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    340× 133×   207× 207× 50× 50× 50×   157×   152×                
import toPath from 'lodash.topath'
 
const setInWithPath = (state, value, first, ...rest) => {
  if (first === undefined) {
    return value
  }
  const next = setInWithPath(state && state[first], value, ...rest)
  if (!state) {
    const initialized = isNaN(first) ? {} : []
    initialized[first] = next
    return initialized
  }
  if (Array.isArray(state)) {
    const copy = [ ...state ]
    copy[first] = next
    return copy
  }
  return {
    ...state,
    [first]: next
  }
}
 
const setIn = (state, field, value) => setInWithPath(state, value, ...toPath(field))
 
export default setIn