All files / src/utils expressionTo.js

45.95% Statements 17/37
27.78% Branches 5/18
66.67% Functions 2/3
45.95% Lines 17/37
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84                                  14x             108x 108x   108x 191x 191x 191x     191x 83x 83x               83x   83x 108x 108x 108x                                         108x             25x              
/*
 * Copyright (c) 2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @flow
 *
 */
 
/*eslint no-loop-func: 0, no-use-before-define: 0*/
 
import resolveToValue from './resolveToValue';
import recast from 'recast';
 
var {types: {namedTypes: types}} = recast;
 
/**
 * Splits a MemberExpression or CallExpression into parts.
 * E.g. foo.bar.baz becomes ['foo', 'bar', 'baz']
 */
function toArray(path: NodePath): Array<string> {
  var parts = [path];
  var result = [];
 
  while (parts.length > 0) {
    path = parts.shift();
    var node = path.node;
    Iif (types.CallExpression.check(node)) {
      parts.push(path.get('callee'));
      continue;
    } else if (types.MemberExpression.check(node)) {
      parts.push(path.get('object'));
      Iif (node.computed) {
        var resolvedPath = resolveToValue(path.get('property'));
        if (resolvedPath !== undefined) {
          result = result.concat(toArray(resolvedPath));
        } else {
          result.push('<computed>');
        }
      } else {
        result.push(node.property.name);
      }
      continue;
    } else Eif (types.Identifier.check(node)) {
      result.push(node.name);
      continue;
    } else if (types.Literal.check(node)) {
      result.push(node.raw);
      continue;
    } else if (types.ThisExpression.check(node)) {
      result.push('this');
      continue;
    } else if (types.ObjectExpression.check(node)) {
      var properties = path.get('properties').map(function(property) {
        return toString(property.get('key')) +
          ': ' +
          toString(property.get('value'));
        });
        result.push('{' + properties.join(', ') + '}');
        continue;
    } else if(types.ArrayExpression.check(node)) {
      result.push('[' + path.get('elements').map(toString).join(', ') + ']');
      continue;
    }
  }
 
  return result.reverse();
}
 
/**
 * Creates a string representation of a member expression.
 */
function toString(path: NodePath): string {
  return toArray(path).join('.');
}
 
export {
  toString as String,
  toArray as Array,
};