All files / src path-translator.js

7.14% Statements 2/28
0% Branches 0/20
0% Functions 0/5
7.14% Lines 2/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 57 58 59 60 61 62 63 64 6528x   28x                                                                                                                            
const get = require('lodash/get');
 
module.exports.transformPathToArray = function(property, jsSpec) {
  const str =
    property.slice(0, 9) === 'instance.' ? property.slice(9) : property;
 
  const pathArr = [];
 
  str
    .split('.')
    .map(item => {
      // 'key[0]' becomes ['key', '0']
      if (item.includes('[')) {
        const index = parseInt(item.match(/\[(.*)\]/)[1]);
        const keyName = item.slice(0, item.indexOf('['));
        return [keyName, index.toString()];
      } else {
        return item;
      }
    })
    .reduce(function(a, b) {
      // flatten!
      return a.concat(b);
    }, [])
    .concat(['']) // add an empty item into the array, so we don't get stuck with something in our buffer below
    .reduce((buffer, curr) => {
      const obj = pathArr.length ? get(jsSpec, pathArr) : jsSpec;
 
      if (get(obj, makeAccessArray(buffer, curr))) {
        if (buffer.length) {
          pathArr.push(buffer);
        }
        if (curr.length) {
          pathArr.push(curr);
        }
        return '';
      } else {
        // attach key to buffer
        return `${buffer}${buffer.length ? '.' : ''}${curr}`;
      }
    }, '');
 
  if (typeof get(jsSpec, pathArr) !== 'undefined') {
    return pathArr;
  } else {
    // if our path is not correct (there is no value at the path),
    // return null
    return null;
  }
};
 
function makeAccessArray(buffer, curr) {
  const arr = [];
 
  if (buffer.length) {
    arr.push(buffer);
  }
 
  if (curr.length) {
    arr.push(curr);
  }
 
  return arr;
}