all files / src/ removeField.js

90% Statements 45/50
69.7% Branches 23/33
100% Functions 6/6
85.29% Lines 29/34
6 statements, 1 function, 3 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 47 48 49 50 51 52 53 54 55 56 13× 13× 13×     13× 13× 13× 13×     13×                           11×                      
const without = (object, key) => {
  const copy = {...object};
  delete copy[key];
  return copy;
};
 
const removeField = (fields, path) => {
  const dotIndex = path.indexOf('.');
  const openIndex = path.indexOf('[');
  const closeIndex = path.indexOf(']');
  Iif (openIndex > 0 && closeIndex !== openIndex + 1) {
    throw new Error('found [ not followed by ]');
  }
  if (openIndex > 0 && (dotIndex < 0 || openIndex < dotIndex)) E{
    // array field
    const key = path.substring(0, openIndex);
    Iif (!Array.isArray(fields[key])) {
      return without(fields, key);
    }
    let rest = path.substring(closeIndex + 1);
    Eif (rest[0] === '.') {
      rest = rest.substring(1);
    }
    Eif (rest) E{
      const copy = [];
      fields[key].forEach((item, index) => {
        const result = removeField(item, rest);
        Iif (Object.keys(result).length) {
          copy[index] = result;
        }
      });
      return copy.length ? {
        ...fields,
        [key]: copy
      } : without(fields, key);
    }
    return without(fields, key);
  }
  if (dotIndex > 0) {
    // subobject field
    const key = path.substring(0, dotIndex);
    const rest = path.substring(dotIndex + 1);
    Iif (!fields[key]) {
      return fields;
    }
    const result = removeField(fields[key], rest);
    return Object.keys(result).length ? {
      ...fields,
      [key]: removeField(fields[key], rest)
    } : without(fields, key);
  }
  return without(fields, path);
};
 
export default removeField;