closures/
closures.rs

1use jsbind::prelude::*;
2
3// Smoke examples for Closure::bind{0..4} and invocation via Function
4fn main() {
5    emlite::init();
6
7    // 0-arg closure returning a number
8    let c0 = Closure::bind0(|| 42);
9    let f0: Function = (&c0).into();
10    let r0 = f0.call(&Any::undefined(), &[]).unwrap().as_::<i32>();
11    Console::get().log(&[Any::from(r0)]);
12
13    // 1-arg closure: add 1
14    let c1 = Closure::bind1(|x: i32| x + 1);
15    let f1: Function = (&c1).into();
16    let r1 = f1
17        .call(&Any::undefined(), &[Any::from(9)])
18        .unwrap()
19        .as_::<i32>();
20    Console::get().log(&[Any::from(r1)]);
21
22    // 2-arg closure: sum
23    let c2 = Closure::bind2(|a: i32, b: i32| a + b);
24    let f2: Function = (&c2).into();
25    let r2 = f2
26        .call(&Any::undefined(), &[Any::from(2), Any::from(3)])
27        .unwrap()
28        .as_::<i32>();
29    Console::get().log(&[Any::from(r2)]);
30
31    // 3-arg closure: format string
32    let c3 = Closure::bind3(|a: i32, b: i32, c: i32| format!("{}-{}-{}", a, b, c));
33    let f3: Function = (&c3).into();
34    let r3 = f3
35        .call(
36            &Any::undefined(),
37            &[Any::from(1), Any::from(2), Any::from(3)],
38        )
39        .unwrap()
40        .as_::<Option<String>>()
41        .unwrap();
42    Console::get().log(&[Any::from(r3)]);
43
44    // 4-arg closure: sum of four
45    let c4 = Closure::bind4(|a: i32, b: i32, c: i32, d: i32| a + b + c + d);
46    let f4: Function = (&c4).into();
47    let r4 = f4
48        .call(
49            &Any::undefined(),
50            &[Any::from(1), Any::from(2), Any::from(3), Any::from(4)],
51        )
52        .unwrap()
53        .as_::<i32>();
54    Console::get().log(&[Any::from(r4)]);
55}