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

97.62% Statements 41/42
91.49% Branches 43/47
100% Functions 8/8
96.67% Lines 29/30
1 statement, 1 function, 10 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   35×       35×           32× 19× 19× 19× 29× 29×   22× 22×   22×     19×   13×        
const isObject = value => value && typeof value === 'object'
 
const deleteWithPath = (state, matcher, path = '') => {
  Iif (state === undefined) {
    return state
  }
 
  if (Array.isArray(state)) {
    let changed = false
    const processed = []
    state.forEach((value, index) => {
      const nextPath = path ? `${path}[${index}]` : String(index)
      if (matcher.test(nextPath)) {
        changed = true
      } else {
        const next = deleteWithPath(value, matcher, nextPath)
        if (next !== value) {
          changed = true
        }
        processed.push(next)
      }
    })
    return changed ? processed : state
  }
  if (isObject(state)) {
    let changed = false
    const processed = {}
    Object.keys(state).forEach(key => {
      const nextPath = path ? `${path}.${key}` : key
      if (matcher.test(nextPath)) {
        changed = true
      } else {
        const next = deleteWithPath(state[key], matcher, nextPath)
        if (next !== state[key]) {
          changed = true
        }
        processed[key] = next
      }
    })
    return changed ? processed : state
  }
  return state
}
 
export default deleteWithPath