From 8937d482edc72e88a1852da2050e1329abdcd80b Mon Sep 17 00:00:00 2001 From: m5l14i11 Date: Wed, 5 Jul 2023 19:45:51 +0300 Subject: [PATCH] replace none by zero --- ta_lib/utils/src/lib.rs | 1 + ta_lib/utils/src/nz.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 ta_lib/utils/src/nz.rs diff --git a/ta_lib/utils/src/lib.rs b/ta_lib/utils/src/lib.rs index 07e0c580..8f0b2cee 100644 --- a/ta_lib/utils/src/lib.rs +++ b/ta_lib/utils/src/lib.rs @@ -1,5 +1,6 @@ pub mod highest; pub mod lowest; +pub mod nz; pub mod stddev; pub mod stoch; pub mod tr; diff --git a/ta_lib/utils/src/nz.rs b/ta_lib/utils/src/nz.rs new file mode 100644 index 00000000..6fc7a4b7 --- /dev/null +++ b/ta_lib/utils/src/nz.rs @@ -0,0 +1,30 @@ +pub fn nz(source: &[Option], replacement: Option) -> Vec { + let replacement = replacement.unwrap_or(0.0); + source.iter().map(|&x| x.unwrap_or(replacement)).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_nz_with_replacement() { + let source = vec![Some(1.0), None, Some(2.0), None]; + let replacement = Some(3.0); + let expected = vec![1.0, 3.0, 2.0, 3.0]; + + let result = nz(&source, replacement); + + assert_eq!(result, expected); + } + + #[test] + fn test_nz_with_default_replacement() { + let source = vec![Some(1.0), None, Some(2.0), None]; + let expected = vec![1.0, 0.0, 2.0, 0.0]; + + let result = nz(&source, None); + + assert_eq!(result, expected); + } +}