Skip to content

Commit

Permalink
chore: format
Browse files Browse the repository at this point in the history
  • Loading branch information
asennikov committed Apr 29, 2024
1 parent dff11a7 commit 908a885
Showing 1 changed file with 35 additions and 11 deletions.
46 changes: 35 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,16 @@ impl<'a> JsonAta<'a> {
self.frame.bind(name, value)
}

pub fn register_function(&self, name: &str, arity: usize, implementation: fn(FunctionContext<'a, '_>, &'a Value<'a>) -> Result<&'a Value<'a>>) {
self.frame.bind(name, Value::nativefn(&self.arena, name, arity, implementation));
pub fn register_function(
&self,
name: &str,
arity: usize,
implementation: fn(FunctionContext<'a, '_>, &'a Value<'a>) -> Result<&'a Value<'a>>,
) {
self.frame.bind(
name,
Value::nativefn(self.arena, name, arity, implementation),
);
}

pub fn evaluate(&self, input: Option<&str>) -> Result<&'a Value<'a>> {
Expand Down Expand Up @@ -112,15 +120,15 @@ impl<'a> JsonAta<'a> {
}

#[cfg(test)]
mod tests{
mod tests {
use super::*;

#[test]
fn register_function_simple() {
let arena = Bump::new();
let jsonata = JsonAta::new("$test()", &arena).unwrap();
jsonata.register_function("test", 0, |ctx, _| Ok(Value::number(ctx.arena, 1)));

let result = jsonata.evaluate(Some(r#"anything"#));

assert_eq!(result.unwrap(), Value::number(&arena, 1));
Expand All @@ -130,8 +138,10 @@ mod tests{
fn register_function_override_now() {
let arena = Bump::new();
let jsonata = JsonAta::new("$now()", &arena).unwrap();
jsonata.register_function("now", 0, |ctx, _| Ok(Value::string(ctx.arena, "time for tea")));

jsonata.register_function("now", 0, |ctx, _| {
Ok(Value::string(ctx.arena, "time for tea"))
});

let result = jsonata.evaluate(Some(r#"anything"#));

assert_eq!(result.unwrap(), Value::string(&arena, "time for tea"));
Expand All @@ -143,12 +153,19 @@ mod tests{
let jsonata = JsonAta::new("$map([1,4,9,16], $squareroot)", &arena).unwrap();
jsonata.register_function("squareroot", 1, |ctx, args| {
let num = &args[0];
return Ok(Value::number(ctx.arena, (num.as_f64()).sqrt()))
return Ok(Value::number(ctx.arena, (num.as_f64()).sqrt()));
});

let result = jsonata.evaluate(Some(r#"anything"#));

assert_eq!(result.unwrap().members().map(|v| v.as_f64()).collect::<Vec<f64>>(), vec![1.0, 2.0, 3.0, 4.0]);
assert_eq!(
result
.unwrap()
.members()
.map(|v| v.as_f64())
.collect::<Vec<f64>>(),
vec![1.0, 2.0, 3.0, 4.0]
);
}

#[test]
Expand All @@ -159,9 +176,16 @@ mod tests{
let num = &args[0];
return Ok(Value::bool(ctx.arena, (num.as_f64()) % 2.0 == 0.0));
});

let result = jsonata.evaluate(Some(r#"anything"#));

assert_eq!(result.unwrap().members().map(|v| v.as_f64()).collect::<Vec<f64>>(), vec![4.0, 16.0]);
assert_eq!(
result
.unwrap()
.members()
.map(|v| v.as_f64())
.collect::<Vec<f64>>(),
vec![4.0, 16.0]
);
}
}

0 comments on commit 908a885

Please sign in to comment.