- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在寻找一种JavaScript表达式语法来指定JSON中的 Action 。 Mapbox's Expressions正是我要寻找的东西,但是我找不到关于是否可以在Mapbox之外使用的任何文档。那可能吗?如果是这样,您将如何做?
最佳答案
它们只是抽象语法树的JSON形式,因此您可以编写自己的执行程序。特别是,根据他们自己的文档,他们似乎遵循以下约定:
let
/ var
函数,该函数允许您创建范围为封闭的let
表达式的变量,这表明它们有某种方式可以将上下文传递给函数。 const OPERATIONS = {};
现在,让我们设置评估器功能。显然,它必须接收将要计算的表达式,而且必须接收可以由操作修改的上下文。
const evaluate = (expression, context = {}) => {
首先,我们通过评估文字本身来处理文字
if (!(expression instanceof Array)) {
return expression;
}
对,现在到真正的交易:
const [operationKey, ...rawParameters] = expression;
const operation = OPERATIONS[operationKey];
我们通过恐慌来处理未知的操作! AAAH!
if (operation == null) {
throw new Error(`Unknown operation ${operationKey}!`);
}
哦,很好,我们知道此操作!现在,我们应该怎么称呼它?
let
可以看到,操作可以创建新的上下文!
return operation(context, rawParameters);
};
对对对,我们已经建立了评估器,但是我们如何实际使用它呢?
OPERATIONS["-"] = (context, [a, b]) => evaluate(a, context) - evaluate(b, context);
OPERATIONS["+"] = (context, [a, b]) => evaluate(a, context) + evaluate(b, context);
好的,那很容易,但是如果我们想接受任意数量的参数呢?
OPERATIONS["*"] = (context, parameters) => parameters
.map(p => evaluate(p, context))
.reduce((accumulator, x) => accumulator * x);
对,现在让我们实现我们所说的那些数组。解决方案很简单,有一个操作可以根据其参数创建数组!
OPERATIONS["array"] = (context, parameters) => parameters
.map(p => evaluate(p, context));
太酷了,但是撒旦本人的邪恶之子呢?
let
和
var
吗?
OPERATIONS["var"] = (context, [variable]) => context[variable];
现在,“tricky”代码
let
既可变又变化上下文!
OPERATIONS["let"] = (context, [...definitions]) => {
是的,我们有一个上下文,但是我们不想在
let
块之外污染它!因此,让我们将其复制到一个新的临时目录中:
const innerContext = { ...context };
现在我们需要循环定义,记住,它们每个都是2个元素:
const body = definitions.pop()
让我们排除一些明显的问题,如果定义中的事物奇数,则用户是错误的!让我们把它们扔在他们丑陋的脸上!让我们使用一个神秘的错误消息只是为了邪恶...
if (definitions.length % 2 === 1) {
throw new Error("Unmatched definitions!");
}
太酷了,现在我们要做的很酷的事情就是创建这些变量:
for (let i = 0; i < definitions.length - 1; i += 2) {
const name = definitions[i];
const value = definitions[i + 1];
在这里,我选择了同一块中的变量可以依赖
innerContext[name] = evaluate(value, innerContext);
}
变量已完成,现在让我们评估一下 body !
return evaluate(body, innerContext);
};
至此完成!这是评估语法树的基础!
// Here we will later define all functions available for the expression language
const OPERATIONS = {};
// Now, let's set up the evaluator function.
// It obviously must receive the expression it will evaluate,
// but also a context that can be modified by operations.
const evaluate = (expression, context = {}) => {
// First, we deal with literals by evaluating them as themselves
if (!(expression instanceof Array)) {
return expression;
}
// Right, now to the real deal:
// let's find out what operation to run and its parameters.
const [operationKey, ...rawParameters] = expression;
const operation = OPERATIONS[operationKey];
// We handle unknown operations by panicking! AAAH!
if (operation == null) {
throw new Error(`Unknown operation ${operationKey}!`);
}
// Oh nice, we know this operation! Now, how should we call it?
// It obviously needs to receive its parameters, as well as the context,
// in case it is one of those pesky stateful operations. Plus, as we
// have seen with Mapbox's `let`, operations can create new contexts!
//
// I propose the following signature, though you can change it for your
// particular preference and use-cases:
//
// First parameter:
// Current context
// Second parameter:
// Array of all of the operation's parameters. This makes for
// easy iteration if the operation is variadic, and simpler stuff
// can still just use deconstruction to have a "fixed" signature.
// We will pass the parameters "raw", not evaluated, so that the
// operation can do whatever evil things it wants to do to them.
// Return value:
// Whatever the operation wants to evaluate to!
return operation(context, rawParameters);
};
// Right, right, we have set up the evaluator, but how do we actually use it?
// We need some operations, let's start with the easy ones to wet our feet:
// Remember how I said above that the parameters array comes in raw?
// We'll need to evaluate them manually inside our operation functions.
OPERATIONS["-"] = (context, [a, b]) => evaluate(a, context) - evaluate(b, context);
OPERATIONS["+"] = (context, [a, b]) => evaluate(a, context) + evaluate(b, context);
// Okay, that was easy, but what if we want
// to accept an arbitrary amount of arguments?
OPERATIONS["*"] = (context, parameters) => parameters
.map(p => evaluate(p, context))
.reduce((accumulator, x) => accumulator * x);
// Right, now let's implement those arrays we spoke of.
// The solution is simple, have an operation that
// creates the array from its parameters!
OPERATIONS["array"] = (context, parameters) => parameters
.map(p => evaluate(p, context));
// Cool, cool, but what about the evil spawns of Satan himself? Let and Var?
// Let's start with the lesser of them:
// Easy, we just read whatever was stored in the context for that variable name!
OPERATIONS["var"] = (context, [variable]) => context[variable];
// Now, the "tricky" one, Let, which is both variadic AND changes the context!
// I'll pull out my braces here because it's gonna be a bit bigger than the
// previous beautiful one-line operations!
OPERATIONS["let"] = (context, [...definitions]) => {
// Right, we have A context, but we don't want to pollute it outside
// the Let block! So let's copy it to a new temporary one:
const innerContext = { ...context
};
// Now we need to loop the definitions, remember, they are 2 elements each:
// A variable name, and its value expression! But first, we need to pick
// out the last argument which is the expression to be executed in the
// resulting context:
const body = definitions.pop()
// Let's get the obvious stuff out of the way, if we have an odd number of
// things in our definitions, the user is wrong! Let's throw it on their
// ugly face! Let's use a cryptic error message just to be evil...
if (definitions.length % 2 === 1) {
throw new Error("Unmatched definitions!");
}
// Cool, now we get to do the cool stuff which is create those variables:
for (let i = 0; i < definitions.length - 1; i += 2) {
const name = definitions[i];
const value = definitions[i + 1];
// Here I made the choice that variables in the same block can depend
// on previous variables, if that's not to your liking, use the parent
// context instead of the one we're modifying at the moment.
innerContext[name] = evaluate(value, innerContext);
}
// Variables are DONE, now let's evaluate the body!
return evaluate(body, innerContext);
};
// Bonus points for reading the snippet code:
// Remember that we are not limited to numeric values,
// anything that JSON accepts we accept too!
// So here's some simple string manipulation.
OPERATIONS["join"] = (context, [separator, things]) => evaluate(things, context)
.flat()
.join(separator);
// And we're done! That is the basic of evaluating a syntax tree!
// Not really relevant to the question itself, just a quick and dirty REPL
(() => {
const input = document.getElementById("input");
const output = document.getElementById("output");
const runSnippet = () => {
let expression;
try {
expression = JSON.parse(input.value);
} catch (e) {
// Let the user type at peace by not spamming errors on partial JSON
return;
}
const result = evaluate(expression);
output.innerText = JSON.stringify(result, null, 2);
}
input.addEventListener("input", runSnippet);
runSnippet();
})();
html {
display: flex;
align-items: stretch;
justify-content: stretch;
height: 100vh;
background: beige;
}
body {
flex: 1;
display: grid;
grid-template-rows: 1fr auto;
grid-gap: 1em;
}
textarea {
padding: 0.5em;
border: none;
background: rgba(0, 0, 0, 0.8);
color: white;
resize: none;
}
<textarea id="input">
[
"let",
"pi", 3.14159,
"radius", 5,
[
"join",
" ",
[
"array",
"a circle with radius",
["var", "radius"],
"has a perimeter of",
[
"*",
2,
["var", "pi"],
["var", "radius"]
]
]
]
]
</textarea>
<pre id="output">
</pre>
关于javascript - 是否可以直接评估Mapbox表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65011797/
目前,由于生成变量的评估,我的Makefile遇到了问题。我降低了复杂性,仅保留了导致问题的基本要素。 读取Makefile时, $(LIST)被评估为文件列表。 在步骤1中,其中一个文件被删除。 在
为什么这 eval 没有调用alert("Summer") ? eval('(caption="Summer";alert(caption))'); 和《夏天》里的台词有关系吗? 最佳答案 Uncau
我正在努力让以下工作正常进行。最初似乎可以工作,但不知何故它停止工作了 var setCommonAttr = "1_row1_common"; var val = document.getEleme
eval('({"suc":true})') 以上错误,应该是: eval('{"suc":true}') 为什么? 最佳答案 当尝试评估时,解释器会看到大括号并认为它是一个 block 开头。将其括
我的页面 A 发出了 ajax 调用并引入了片段 B。该片段被添加到 DOM 中,并且该片段中的所有脚本都经过了评估。在该代码片段中,我有 2 个脚本标签: function doOptions()
这里是javascript代码: var test = { "h" : function (a) {return a;}, "say" : "hello" }; 第一次运行: test
我正在查看一些工作代码,并遇到了这一行: eval("\$element = \"$element\";"); 我真的很困惑为什么任何 PHP 开发人员都会写这一行。除了给自己设置一个变量之外,这还有
谁能帮我解决以下问题: 我有这样的代码: if(cond1 && cond2 && .. && cond10) 这里,cond1 是昂贵的操作,其输出是 boolean 值。 现在我的问题是,当 co
**摘要:**华为AppCube应用魔方顺利通过信通院评估,被认证为具备 “低代码开发平台通用能力”的企业服务平台。 本文分享自华为云社区《华为AppCube通过中国信通院“低代码开发平台通用能力要求
我正在尝试通过 PHP 从图像的 EXIF 数据中获取焦距。 这是我目前得到的代码: $exif = exif_read_data("$photo"); $length10 = $exif['Foca
我想使用id =“key”将一个类添加到元素中,但是为什么不起作用?我是js的初学者:这是代码: audio.classList.add('yellow'); 这是错误: null is not an
这是我的 XML: QueWay Password Recovery 现在我想用 php 用 xpath 选择文本“QueWay”。到目前为止我所拥有的一切都很好: $xml =
使用下面的代码,即使我输入的数字大于 18,我也会得到这个结果。 运行:你今年多大? 21你还没有达到成年年龄!构建成功(总时间:3 秒) 我是java新手,正在尝试自学,有人可以帮忙吗? impor
我正在阅读 http://www.cran.r-project.org/doc/manuals/R-lang.pdf手册第 4.3 章,我就是不明白。也许有人可以给我一个快速的解释,为什么 R 的行为
在这个实现中,每次都会评估 hand 并返回另一个列表吗? foreach (Card card in hand.Cards) { } 我们应该用下面的实现替换上面的实现吗? var cards =
我正在制作 LINQ lambda 表达式: Expression> add = (x, y) => x + y; 但现在我将如何评估它,比如说找到 2+3? 最佳答案 这应该适合你: var su
我正在制作一个语言解释器,我已经到了需要评估 if 语句的地步。起初我认为这很简单,我能够让我的解释器评估简单的 if 条件,10 == 10 但是当我试图让它评估更复杂的条件时, 10 == 10
我正在尝试以下代码,该代码向 RDD 中的每一行添加一个数字,并使用 PySpark 返回 RDD 列表。 from pyspark.context import SparkContext file
在阅读了很多关于 Lisp eval-when 运算符的文档后,我仍然无法理解它的用途,我知道使用这个运算符我可以控制表达式的计算时间,但我做不到找出任何可能适用的示例? 最好的问候,utxee. 最
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 要求我们推荐或查找工具、库或最喜欢的场外资源的问题对于 Stack Overflow 来说是偏离主题的,
我是一名优秀的程序员,十分优秀!