1use crate::math::{
2 avg::average,
3 utils::{run_with_function_with_cell_paths, run_with_function_with_cell_paths_const},
4};
5use nu_engine::command_prelude::*;
6use std::cmp::Ordering;
7
8#[derive(Clone)]
9pub struct MathMedian;
10
11impl Command for MathMedian {
12 fn name(&self) -> &str {
13 "math median"
14 }
15
16 fn signature(&self) -> Signature {
17 Signature::build("math median")
18 .input_output_types(vec![
19 (Type::List(Box::new(Type::Number)), Type::Number),
20 (Type::List(Box::new(Type::Duration)), Type::Duration),
21 (Type::List(Box::new(Type::Filesize)), Type::Filesize),
22 (Type::Range, Type::Number),
23 (Type::table(), Type::record()),
24 (Type::record(), Type::record()),
25 ])
26 .allow_variants_without_examples(true)
27 .rest(
28 "columns",
29 SyntaxShape::CellPath,
30 "The cell-paths/columns to operate on.",
31 )
32 .category(Category::Math)
33 }
34
35 fn description(&self) -> &str {
36 "Computes the median of a list of numbers."
37 }
38
39 fn search_terms(&self) -> Vec<&str> {
40 vec!["middle", "statistics"]
41 }
42
43 fn is_const(&self) -> bool {
44 true
45 }
46
47 fn run(
48 &self,
49 engine_state: &EngineState,
50 stack: &mut Stack,
51 call: &Call,
52 input: PipelineData,
53 ) -> Result<PipelineData, ShellError> {
54 run_with_function_with_cell_paths(engine_state, stack, call, input, median)
55 }
56
57 fn run_const(
58 &self,
59 working_set: &StateWorkingSet,
60 call: &Call,
61 input: PipelineData,
62 ) -> Result<PipelineData, ShellError> {
63 run_with_function_with_cell_paths_const(working_set, call, input, median)
64 }
65
66 fn examples(&self) -> Vec<Example<'_>> {
67 vec![
68 Example {
69 description: "Compute the median of a list of numbers.",
70 example: "[3 8 9 12 12 15] | math median",
71 result: Some(Value::test_float(10.5)),
72 },
73 Example {
74 description: "Compute the medians of the columns of a table.",
75 example: "[{a: 1 b: 3} {a: 2 b: -1} {a: -3 b: 5}] | math median",
76 result: Some(Value::test_record(record! {
77 "a" => Value::test_int(1),
78 "b" => Value::test_int(3),
79 })),
80 },
81 Example {
82 description: "Find the median of a list of file sizes.",
83 example: "[5KB 10MB 200B] | math median",
84 result: Some(Value::test_filesize(5 * 1_000)),
85 },
86 Example {
87 description: "Compute the median of list-valued columns in a record.",
88 example: "{alice: [3 1 2], bob: [4 5 6]} | math median",
89 result: Some(Value::test_record(record! {
90 "alice" => Value::test_int(2),
91 "bob" => Value::test_int(5),
92 })),
93 },
94 Example {
95 description: "Compute the median of a single column using a cell path.",
96 example: "{alice: [3 1 2], bob: [4 5 6]} | math median alice",
97 result: Some(Value::test_record(record! {
98 "alice" => Value::test_int(2),
99 "bob" => Value::list(
100 vec![Value::test_int(4), Value::test_int(5), Value::test_int(6)],
101 Span::test_data(),
102 ),
103 })),
104 },
105 ]
106 }
107}
108
109enum Pick {
110 MedianAverage,
111 Median,
112}
113
114pub fn median(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
115 for value in values {
117 match value {
118 Value::Int { .. }
119 | Value::Float { .. }
120 | Value::Duration { .. }
121 | Value::Filesize { .. } => {}
122 Value::Error { error, .. } => return Err(*error.clone()),
123 other => {
124 return Err(ShellError::OnlySupportsThisInputType {
125 exp_input_type: crate::math::utils::NUMERIC_INPUT_TYPES.into(),
126 wrong_type: other.get_type().to_string(),
127 dst_span: head,
128 src_span: other.span(),
129 });
130 }
131 }
132 }
133
134 let mut sorted = values
135 .iter()
136 .filter(|x| !x.as_float().is_ok_and(f64::is_nan))
137 .collect::<Vec<_>>();
138
139 if sorted.is_empty() {
140 return Err(ShellError::UnsupportedInput {
141 msg: "Empty input".to_string(),
142 input: "value originates from here".into(),
143 msg_span: head,
144 input_span: span,
145 });
146 }
147
148 sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
149
150 let take = if sorted.len().is_multiple_of(2) {
151 Pick::MedianAverage
152 } else {
153 Pick::Median
154 };
155
156 match take {
157 Pick::Median => {
158 let idx = sorted.len() / 2;
159 Ok(sorted[idx].to_owned().to_owned())
161 }
162 Pick::MedianAverage => {
163 let idx_end = sorted.len() / 2;
164 let idx_start = idx_end - 1;
165 let left = sorted[idx_start].to_owned().to_owned();
166 let right = sorted[idx_end].to_owned().to_owned();
167 average(&[left, right], span, head)
168 }
169 }
170}
171
172#[cfg(test)]
173mod test {
174 use super::*;
175
176 #[test]
177 fn test_examples() -> nu_test_support::Result {
178 nu_test_support::test().examples(MathMedian)
179 }
180
181 #[test]
182 fn test_median_with_nan_values() {
183 let span = Span::test_data();
189 let values = vec![
190 Value::test_float(f64::NAN),
191 Value::test_float(f64::NAN),
192 Value::test_float(1.0),
193 Value::test_float(2.0),
194 Value::test_float(3.0),
195 Value::test_float(4.0),
196 ];
197
198 let result = median(&values, span, span).unwrap();
199 assert_eq!(result, Value::test_float(2.5));
200 }
201}