Skip to content

Instantly share code, notes, and snippets.

@bepitulaz
Created August 17, 2021 16:54
Show Gist options
  • Save bepitulaz/870868b5fe5fed87d21911d415a85891 to your computer and use it in GitHub Desktop.
Save bepitulaz/870868b5fe5fed87d21911d415a85891 to your computer and use it in GitHub Desktop.
Calculating simple moving average in Rust and target Node native module.
use node_bindgen::derive::node_bindgen;
#[node_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