all files / src/ read.js

96% Statements 24/25
95.83% Branches 23/24
100% Functions 1/1
95.83% Lines 23/24
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      1157× 255×   902× 902× 54×   848× 848× 848×   240×   608× 174×   173× 173× 173×     173×   170× 99×   71×   434×        
/**
 * Reads any potentially deep value from an object using dot and array syntax
 */
const read = (path, object) => {
  if (!path || !object) {
    return object;
  }
  const dotIndex = path.indexOf('.');
  if (dotIndex === 0) {
    return read(path.substring(1), object);
  }
  const openIndex = path.indexOf('[');
  const closeIndex = path.indexOf(']');
  if (dotIndex >= 0 && (openIndex < 0 || dotIndex < openIndex)) {
    // iterate down object tree
    return read(path.substring(dotIndex + 1), object[path.substring(0, dotIndex)]);
  }
  if (openIndex >= 0 && (dotIndex < 0 || openIndex < dotIndex)) {
    if (closeIndex < 0) {
      throw new Error('found [ but no ]');
    }
    const key = path.substring(0, openIndex);
    const index = path.substring(openIndex + 1, closeIndex);
    Iif (!index.length) {
      return object[key];
    }
    if (openIndex === 0) {
      return read(path.substring(closeIndex + 1), object[index]);
    }
    if (!object[key]) {
      return undefined;
    }
    return read(path.substring(closeIndex + 1), object[key][index]);
  }
  return object[path];
};
 
export default read;