From d3aa7eb7ef308d701319c96bbb9131c639b1386d Mon Sep 17 00:00:00 2001 From: Darren Schroeder <343840+fdncred@users.noreply.github.com> Date: Thu, 14 Nov 2024 15:08:03 -0600 Subject: [PATCH] add min and max --- crates/nu-command/src/filters/agg_by.rs | 54 ++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 2 deletions(-) diff --git a/crates/nu-command/src/filters/agg_by.rs b/crates/nu-command/src/filters/agg_by.rs index 3c2dc3ce9c..bd19ba35d3 100644 --- a/crates/nu-command/src/filters/agg_by.rs +++ b/crates/nu-command/src/filters/agg_by.rs @@ -188,7 +188,7 @@ fn groups_to_table( record_map.insert("count".to_string(), Value::int(items.len() as i64, span)); if let Some(sum_col) = maybe_sum_column.clone() { - match sum_celllpath(sum_col, &items, span) { + match sum_celllpath(sum_col.clone(), &items, span) { Ok((sum_col_name, sum)) => { // add sum record_map @@ -206,6 +206,20 @@ fn groups_to_table( record_map.insert("error".to_string(), Value::error(err, span)); } } + + match minmax_celllpath(sum_col, &items, span) { + Ok((min_col_name, min, max)) => { + // add min + record_map + .insert(min_col_name.clone() + "_min", Value::float(min, span)); + // add max + record_map.insert(min_col_name + "_max", Value::float(max, span)); + } + Err(err) => { + // It seems a little odd to be adding an error to the record + record_map.insert("error".to_string(), Value::error(err, span)); + } + } } Value::record(record_map, span) @@ -223,7 +237,7 @@ fn sum_celllpath(column: Value, items: &[Value], span: Span) -> Result<(String, v.clone() .follow_cell_path(&val.members, false) .unwrap_or_else(|_| Value::float(0.0, span)) - .as_float() + .coerce_float() .unwrap_or(0.0) }) .sum(); @@ -236,6 +250,42 @@ fn sum_celllpath(column: Value, items: &[Value], span: Span) -> Result<(String, } } +fn minmax_celllpath( + column: Value, + items: &[Value], + span: Span, +) -> Result<(String, f64, f64), ShellError> { + if let Value::CellPath { val, .. } = column { + let collection = items + .iter() + .map(|v| { + v.clone() + .follow_cell_path(&val.members, false) + .unwrap_or_else(|_| Value::float(0.0, span)) + .coerce_float() + .unwrap_or(0.0) + }) + .collect::>(); + + Ok(( + val.to_column_name(), + *collection + .iter() + .min_by(|a, b| a.total_cmp(b)) + .unwrap_or(&0.0), + *collection + .iter() + .max_by(|a, b| a.total_cmp(b)) + .unwrap_or(&0.0), + )) + } else { + Err(ShellError::TypeMismatch { + err_message: format!("Only CellPath's are allowed. Found {}.", column.get_type()), + span, + }) + } +} + #[cfg(test)] mod test { use super::*;