使用PegJS(对其他建议开放)等方式寻找解决方案,以递归方式查找和扩展变量。
程序可以将变量设置为其他变量或数字
给出这样的结构:
{$a: '1', $b: '$a + 2', $c: '$b + 10'}
$a
// looks up $a, expands to 1
$b
// looks up $b, finds $a + 2, looks up $a and expands to 1 + 2
$c
// looks up $c, finds $b + 10, looks up $b and finds $a + 2, looks up $a and expands to 1 + 2
实现这一目标的最佳方式(工具或其他方式)是什么?
答案 0 :(得分:0)
这是一个可以帮助您入门的简单解决方案。在初始值设定项中定义obj = {}
,因为您希望在解析时使对象可用,以便在找到密钥时对其进行缓存。
{
var obj = {};
}
obj =
"{" _* keyPair* "}"
{
return obj;
}
keyPair =
key:key ":" _* val:singleQuoted _*
{
obj[key] = val;
}
key =
$("$" word)
expression =
key:key _* "+" _* num:num
{
return obj[key] + num;
}
singleQuoted =
"'" exp:(expression / num) "'" ","?
{
return exp;
}
num =
num:$([0-9]+)
{
return parseInt(num);
}
word =
$([A-Za-z]+)
_ =
" "