js_sandbox/
util.rs

1// Copyright (c) 2020-2021 Jan Haller. zlib/libpng license.
2
3use crate::{AnyError, JsValue, Script};
4
5/// Evaluates a standalone Javascript expression, and returns the result as a JSON value.
6///
7/// If there is an error, Err will be returned.
8/// This function is primarily useful for small standalone experiments. Usually, you would want to use the [`Script`](struct.Script.html) struct
9/// for more sophisticated Rust->JS interaction.
10pub fn eval_json(js_expr: &str) -> Result<JsValue, AnyError> {
11	let code = format!("
12		function __rust_expr() {{
13			return ({expr});
14		}}
15	", expr = js_expr);
16
17	let mut script = Script::from_string(&code)?;
18	script.call_json("__rust_expr", &JsValue::Null)
19}