Skip to main content

rhai_sci/
sets.rs

1use rhai::plugin::*;
2
3#[export_module]
4pub mod set_functions {
5    use rhai::{Array, EvalAltResult};
6
7    /// Returns the set union of two arrays.
8    /// ```typescript
9    /// let set1 = [7, 1, 7, 7, 4];
10    /// let set2 = [7, 0, 4, 4, 0];
11    /// let u = union(set1, set2);
12    /// assert_eq(u, [0, 1, 4, 7]);
13    /// ```
14    #[rhai_fn(name = "union", return_raw)]
15    pub fn union(arr1: Array, arr2: Array) -> Result<Array, Box<EvalAltResult>> {
16        let mut x = arr1.clone();
17        let y = arr2.clone();
18        x.extend(y);
19        crate::misc_functions::unique(&mut x)
20    }
21
22    /// Performs set intersection of two arrays
23    /// ```typescript
24    ///  let set1 = [7, 1, 7, 7, 4];
25    ///  let set2 = [7, 0, 4, 4, 0];
26    /// let x = intersect(set1, set2);
27    /// assert_eq(x, [4, 7]);
28    /// ```
29    #[rhai_fn(name = "intersect", return_raw)]
30    pub fn intersect(arr1: Array, arr2: Array) -> Result<Array, Box<EvalAltResult>> {
31        let array2 = arr2
32            .into_iter()
33            .map(|x| format!("{:?}", x).to_string())
34            .collect::<Vec<String>>();
35        let mut new_arr = vec![];
36        for el in arr1 {
37            if array2.contains(&format!("{:?}", el).to_string()) {
38                new_arr.push(el);
39            }
40        }
41        Ok(crate::misc_functions::unique(&mut new_arr).unwrap())
42    }
43}