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

96.3% Statements 52/54
94.44% Branches 34/36
100% Functions 6/6
92.86% Lines 26/28
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46    108×   107× 39×       36× 25×         11×   68×         62× 40× 40× 40×   22×          
import toPath from 'lodash.topath'
 
const deleteInWithPath = (state, first, ...rest) => {
  if (state === undefined || first === undefined) {
    return state
  }
  if (rest.length) {
    if (Array.isArray(state)) {
      Eif (first < state.length) {
        const copy = [ ...state ]
        copy[first] = deleteInWithPath(state && state[ first ], ...rest)
        return copy
      }
      return state
    }
    if (first in state) {
      return {
        ...state,
        [first]: deleteInWithPath(state && state[ first ], ...rest)
      }
    }
    return state
  }
  if (Array.isArray(state)) {
    Iif (isNaN(first)) {
      throw new Error('Cannot delete non-numerical index from an array')
    }
    if (first < state.length) {
      const copy = [ ...state ]
      copy.splice(first, 1)
      return copy
    }
    return state
  }
  if (first in state) {
    const copy = { ...state }
    delete copy[ first ]
    return copy
  }
  return state
}
 
const deleteIn = (state, field) => deleteInWithPath(state, ...toPath(field))
 
export default deleteIn