1use wasm_bindgen::prelude::*;
2
3#[wasm_bindgen]
5#[derive(Clone, Debug, PartialEq)]
6pub struct ClosedInterval {
7 start: f32,
9 end: f32,
11}
12
13#[wasm_bindgen]
14impl ClosedInterval {
15 #[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 #[wasm_bindgen(getter, return_description = "The start of the interval.")]
28 pub fn start(&self) -> f32 {
29 self.start
30 }
31
32 #[wasm_bindgen(getter, return_description = "The end of the interval.")]
34 pub fn end(&self) -> f32 {
35 self.end
36 }
37
38 #[wasm_bindgen(getter, return_description = "The length of the interval.")]
40 pub fn length(&self) -> f32 {
41 self.end - self.start
42 }
43
44 #[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 #[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 #[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}