sir*_*tty 1 javascript parsing node.js
我正在构建一个节点应用程序,在该应用程序中,用户可以(理想地)使用一系列JSON对象为地理数据定义样式:
{
"style":
{
"test": "year",
"condition": "<= 1954 AND >= 1936",
"color": "red"
}
}
Run Code Online (Sandbox Code Playgroud)
在上述情况下,我喜欢将该样式评估为
if (year <= 1954 && year >= 1936){
object.color = red;
}
Run Code Online (Sandbox Code Playgroud)
有没有简单的方法来解析+评估此类表达式/从此类对象构建它们?我对让人们将使用<=,> =,||,&&等构建的复杂表达式串在一起特别感兴趣。
如果可能的话,我想避免使用eval()。
如果您不希望使用eval,则必须编写自己的小解析器并创建如下定义语言:
"condition": ["and", ["<=", 1954], [">=", 1936]],
Run Code Online (Sandbox Code Playgroud)
您可以考虑这是部分实现:
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];
}
}
Run Code Online (Sandbox Code Playgroud)
这是您将如何使用它:
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"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2210 次 |
| 最近记录: |