From 8114b1a3208f012deef7c0edd1535c5fcce808c8 Mon Sep 17 00:00:00 2001 From: Simon Gardling Date: Mon, 14 Feb 2022 15:00:16 -0500 Subject: [PATCH] refactor --- src/lib.rs | 75 +++++++++++++++++++++++++++--------------------------- 1 file changed, 37 insertions(+), 38 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 9099dc1..001bd8b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,42 +10,6 @@ static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; pub type DrawResult = Result>; -// Creates and does the math for creating all the rectangles under the graph -#[inline(always)] -fn integral_rectangles( - min_x: f32, step: f32, num_interval: usize, func: &dyn Fn(f64) -> f64, -) -> (Vec<(f32, f32, f32)>, f32) { - let data2: Vec<(f32, f32, f32)> = (0..num_interval) - .map(|e| { - let x: f32 = ((e as f32) * step) + min_x; - - // Makes sure rectangles are properly handled on x values below 0 - let x2: f32 = match x > 0.0 { - true => x + step, - false => x - step, - }; - - let tmp1: f32 = func(x as f64) as f32; - let tmp2: f32 = func(x2 as f64) as f32; - - // Chooses the y value who's absolute value is the smallest - let y: f32 = match tmp2.abs() > tmp1.abs() { - true => tmp1, - false => tmp2, - }; - - if !y.is_nan() { - (x, x2, y) - } else { - (0.0, 0.0, 0.0) - } - }) - .filter(|ele| ele != &(0.0, 0.0, 0.0)) - .collect(); - let area: f32 = data2.iter().map(|(_, _, y)| y * step).sum(); // sum of all rectangles' areas - (data2, area) -} - /// Result of screen to chart coordinates conversion. #[wasm_bindgen] pub struct Point { @@ -145,8 +109,7 @@ impl ChartManager { None => panic!("use_front_cache is true, but front_cache is None!"), }, false => { - let output: (Vec<(f32, f32, f32)>, f32) = - integral_rectangles(self.min_x, step, self.num_interval, &func); + let output: (Vec<(f32, f32, f32)>, f32) = self.integral_rectangles(step, &func); self.front_cache = Some(output.clone()); output } @@ -212,6 +175,42 @@ impl ChartManager { Ok(chart) } + + // Creates and does the math for creating all the rectangles under the graph + #[inline(always)] + fn integral_rectangles( + &self, step: f32, func: &dyn Fn(f64) -> f64, + ) -> (Vec<(f32, f32, f32)>, f32) { + let data2: Vec<(f32, f32, f32)> = (0..self.num_interval) + .map(|e| { + let x: f32 = ((e as f32) * step) + self.min_x; + + // Makes sure rectangles are properly handled on x values below 0 + let x2: f32 = match x > 0.0 { + true => x + step, + false => x - step, + }; + + let tmp1: f32 = func(x as f64) as f32; + let tmp2: f32 = func(x2 as f64) as f32; + + // Chooses the y value who's absolute value is the smallest + let y: f32 = match tmp2.abs() > tmp1.abs() { + true => tmp1, + false => tmp2, + }; + + if !y.is_nan() { + (x, x2, y) + } else { + (0.0, 0.0, 0.0) + } + }) + .filter(|ele| ele != &(0.0, 0.0, 0.0)) + .collect(); + let area: f32 = data2.iter().map(|(_, _, y)| y * step).sum(); // sum of all rectangles' areas + (data2, area) + } } #[wasm_bindgen]