解析简单的三元表达式

319 阅读1分钟
/**
 * Ternary Expression Parser
 *
 * @param expression 表达式字符串
 * source 数据源
 * @private
 */
private parseTernary(expression, source) {
  let res = expression;
  while (res.indexOf('?') > 0) {
    const i = res.lastIndexOf('?');
    const prefix = res.substr(0, i);
    const suffix = _.split(res.substr(i + 1), ':');
    // Expression Parser
    const prefixIndex = prefix.lastIndexOf(':');
    let checkExpression;
    if (prefixIndex > 0) {
      res = prefix.substr(0 , prefixIndex);
      checkExpression = prefix.substr(prefixIndex + 1);
    } else {
      checkExpression = prefix;
      res = '';
    }
    // if single quotes, it need to take the value from the source
    const getValue = (key) => {
      const param = _.trim(key);
      return param.indexOf(''') > -1 ? _.trim(param, ''') : source[param];
    };
    // get the result of check expression
    let check = true;
    const params = _.split(checkExpression, />|<|={2,3}/);
    if (params.length === 2) {
        const symbol =  checkExpression.substr(params[0].length, checkExpression.length - params[0].length - params[1].length);
        const param1 = getValue(params[0]);
        const param2 = getValue(params[1]);
        switch (symbol) {
          case '>':
            check = param1 > param2;
            break;
          case '<':
            check = param1 < param2;
            break;
           case '==':
             check = param1 == param2;
             break;
          case '===':
            check = param1 === param2;
            break;
          default:
            break;
        }
    } else {
      check = getValue(params[0]);
    }
    res = res + (check ? getValue(suffix[0]) : getValue(suffix[1]));
  }
  return res;
}