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); + } +}