1

我正在构建一个节点应用程序,其中用户(理想情况下)能够使用一系列 JSON 对象定义样式 - 用于地理数据:

{
    "style":
        {
            "test": "year",
            "condition": "<= 1954 AND >= 1936",
            "color": "red"
        }
}

在上述情况下,我喜欢将这种风格评估为

if (year <= 1954 && year >= 1936){
    object.color = red;
}

有没有一种简单的方法来解析 + 评估这样的表达式/从这样的对象构建它们?我对让人们将使用 <=、>=、||、&& 等构建的复杂表达式串在一起特别感兴趣。

如果可能的话,我想避免使用 eval()。

4

2 回答 2

5

如果您不想使用 eval,则必须编写自己的小解析器并创建如下定义语言:

"condition": ["and", ["<=", 1954], [">=", 1936]],

这是您可以考虑的部分实现:

function do_and(args, value)
{
  for (var i = 0; i < args.length; ++i) {
    if (!evaluate(args[i], value)) {
      return false;
    }
  }
  return true;
}

function evaluate(condition, value)
{
  switch (condition[0]) {
    case "and":
      return do_and(condition.slice(1), value);

    case "<=":
      return value <= condition[1];

    case ">=":
      return value >= condition[1];
  }
}

这是你将如何使用它:

var style = {
    "test": "year",
    "condition": ["and", ["<=", 1954], [">=", 1936]],
    "color": "red"
}, context = {
  "year": 1940
};    

if (evaluate(style.condition, context[style.test])) {
  console.log(style.color); // "red"
}

演示

于 2013-07-04T04:05:19.330 回答
1

就像是

var obj = JSON.parse(str);
switch (obj.style.operator){
    case '=':
    if (window[obj.style.condition] === obj.style){//assuming that the conditions are global
        object.color = obj.style;
    }
    break;
    ...
}
于 2013-07-04T03:36:06.117 回答