index/utils/
interval.rs

1use wasm_bindgen::prelude::*;
2
3/// A ClosedInterval represents a closed interval [start, end].
4#[wasm_bindgen]
5#[derive(Clone, Debug, PartialEq)]
6pub struct ClosedInterval {
7    /// The start of the interval.
8    start: f32,
9    /// The end of the interval.
10    end: f32,
11}
12
13#[wasm_bindgen]
14impl ClosedInterval {
15    /// Creates a new Interval from a start and end value.
16    #[wasm_bindgen(constructor, return_description = "A new interval.")]
17    pub fn new(
18        #[wasm_bindgen(param_description = "The start of the interval.")]
19        start: f32,
20        #[wasm_bindgen(param_description = "The end of the interval.")]
21        end: f32
22    ) -> ClosedInterval {
23        ClosedInterval { start, end }
24    }
25
26    /// Returns the start of the interval.
27    #[wasm_bindgen(getter, return_description = "The start of the interval.")]
28    pub fn start(&self) -> f32 {
29        self.start
30    }
31
32    /// Returns the end of the interval.
33    #[wasm_bindgen(getter, return_description = "The end of the interval.")]
34    pub fn end(&self) -> f32 {
35        self.end
36    }
37
38    /// Returns the length of the interval.
39    #[wasm_bindgen(getter, return_description = "The length of the interval.")]
40    pub fn length(&self) -> f32 {
41        self.end - self.start
42    }
43
44    /// Returns the midpoint of the interval.
45    #[wasm_bindgen(return_description = "The midpoint of the interval.")]
46    pub fn midpoint(&self) -> f32 {
47        (self.start + self.end) * 0.5
48    }
49
50    /// Samples the interval at a given number of points.
51    #[wasm_bindgen(return_description = "The sampled points of the interval.")]
52    pub fn sample(
53        &self,
54        #[wasm_bindgen(param_description = "The number of points to sample.")]
55        num_points: usize
56    ) -> Vec<f32> {
57        let step = self.length() / (num_points as f32 - 1.0);
58        (0..num_points)
59            .map(|i| self.start + step * (i as f32))
60            .collect()
61    }
62
63    /// Checks if a number is contained within the interval.
64    #[wasm_bindgen(return_description = "Whether the number is contained within the interval.")]
65    pub fn contains(
66        &self,
67        #[wasm_bindgen(param_description = "The number to check if it is contained.")]
68        number: f32
69    ) -> bool {
70        number >= self.start && number <= self.end
71    }
72}