Created
August 17, 2021 16:50
-
-
Save bepitulaz/88eb126ef1dd2ccd80d890aeee0c77a5 to your computer and use it in GitHub Desktop.
Calculate simple moving average in Rust and targeting WASM.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use wasm_bindgen::prelude::*; | |
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global | |
// allocator. | |
#[cfg(feature = "wee_alloc")] | |
#[global_allocator] | |
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; | |
#[wasm_bindgen] | |
extern "C" { | |
#[wasm_bindgen(js_namespace = console)] | |
fn log(s: String); | |
} | |
#[wasm_bindgen] | |
pub fn simple_moving_average(array_prices: Vec<f64>, window: f64) -> Vec<f64> { | |
let interval = window as usize; | |
let mut index = interval - 1; | |
let length = array_prices.len() + 1; | |
let mut results = Vec::new(); | |
while index < length { | |
index = index + 1; | |
let start_index = index - interval; | |
let interval_slice = &array_prices[start_index..index-1]; | |
let sum: f64 = interval_slice.iter().sum(); | |
let interval_float = interval as f64; | |
results.push(sum / interval_float); | |
} | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment