Skip to content

Commit

Permalink
Fix mean on empty arrays (foundry-rs#2612)
Browse files Browse the repository at this point in the history
* Fix mean on empty arrays

* Update code style

* Add empty slice tests
  • Loading branch information
Rubilmax authored and iFrostizz committed Nov 9, 2022
1 parent feb8326 commit 0d4253d
Showing 1 changed file with 26 additions and 8 deletions.
34 changes: 26 additions & 8 deletions common/src/calc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ pub fn mean<T>(values: &[T]) -> U256
where
T: Into<U256> + Copy,
{
if values.is_empty() {
return U256::zero()
}

values.iter().copied().fold(U256::zero(), |sum, val| sum + val.into()) / values.len()
}

Expand All @@ -18,30 +22,44 @@ pub fn median_sorted<T>(values: &[T]) -> T
where
T: Add<Output = T> + Div<u64, Output = T> + From<u64> + Copy,
{
if values.is_empty() {
return 0u64.into()
}

let len = values.len();
if len > 0 {
let mid = len / 2;
if len % 2 == 0 {
(values[mid - 1] + values[mid]) / 2u64
} else {
values[mid]
}
let mid = len / 2;
if len % 2 == 0 {
(values[mid - 1] + values[mid]) / 2u64
} else {
0u64.into()
values[mid]
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn calc_mean_empty() {
let values: [u64; 0] = [];
let m = mean(&values);
assert_eq!(m, U256::zero());
}

#[test]
fn calc_mean() {
let values = [0u64, 1u64, 2u64, 3u64, 4u64, 5u64, 6u64];
let m = mean(&values);
assert_eq!(m, 3u64.into());
}

#[test]
fn calc_median_empty() {
let values: Vec<u64> = vec![];
let m = median_sorted(&values);
assert_eq!(m, 0);
}

#[test]
fn calc_median() {
let mut values = vec![29, 30, 31, 40, 59, 61, 71];
Expand Down

0 comments on commit 0d4253d

Please sign in to comment.